Vue3 動態 Web title

Vue 動態 Title

  • Pinia全局綁定title 與 切換時改變title
  • 綁定body 設定屬性 setAttribute class 改變body class
  • 監控 watchEffect 改變
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    import { defineStore } from 'pinia';

    export const usePageStore = defineStore('page', () => {

    const setPageClass = (pageClass:string) => {
    document.querySelector('body')?.setAttribute('class', pageClass);
    }
    const getPageClass=()=>{
    let pageClass:any | string =localStorage.getItem('pageClass');
    switch (pageClass) {
    case pageClass:
    document.querySelector('body')?.setAttribute('class', pageClass);
    break
    }
    }
    const changeTitleTag = (title: string) => {
    const titleTag = document.querySelector('title');

    if (titleTag != null) {
    titleTag.innerText = '採購系統'+' | '+title;
    }
    }

    return{
    setPageClass,getPageClass,changeTitleTag
    }
    })

    引入頁面
    首頁頁面

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <template>
    <div>{{ title }}</div>
    </template>

    <script setup lang="ts">
    import { ref, onMounted,watchEffect } from 'vue'
    import { usePageStore } from '../stores/titleTag'

    const storePageTag = usePageStore()
    const {getPageClass,changeTitleTag,setPageClass} = storePageTag
    const title = ref<string>('首頁')
    const pageClass = ref<string>('homePage')
    watchEffect(() => {
    getPageClass();
    setPageClass(pageClass.value)
    })
    onMounted(() => {
    changeTitleTag(title.value);
    });
    </script>

    登入頁面

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <template>
    <div>{{ title }}</div>
    </template>

    <script setup lang="ts">
    import { ref, onMounted,watchEffect } from 'vue'
    import { usePageStore } from '../stores/titleTag'
    const storePageTag = usePageStore()
    const {getPageClass,changeTitleTag,setPageClass} = storePageTag
    const title = ref<string>('請先登入')
    const pageClass = ref<string>('loginPage')
    watchEffect(() => {
    getPageClass();
    setPageClass(pageClass.value)
    })
    onMounted(() => {
    changeTitleTag(title.value);

    });
    </script>