vue3/vite 动态路由——动态修改标题(title)

目录

vue3/vite 动态路由——动态修改标题(title)_第1张图片

1.main.js  导入store

vue3/vite 动态路由——动态修改标题(title)_第2张图片

import {createApp} from 'vue'
import App from './App.vue'
import router from "./router";
import "./router/permission";
import store from "./store";

const app = createApp(App)

app.use(router)
app.use(store)

app.mount('#app')

 2.store/index.js  导出store

import {createPinia} from "pinia/dist/pinia";

const store = createPinia()

export default store

3. store/modules/settings  定义store

import defaultSettings from '@/settings'
import { useDynamicTitle } from '@/utils/dynamicTitle'
import {defineStore} from "pinia/dist/pinia";

const { dynamicTitle } = defaultSettings

const storageSetting = JSON.parse(localStorage.getItem('storageSetting')) || ''

const useSettingsStore = defineStore(
    'settings',
    {
        state: () => ({
            title: '',
            dynamicTitle: storageSetting.dynamicTitle === undefined ? dynamicTitle : storageSetting.dynamicTitle
        }),
        actions: {
            // 设置网页标题
            setTitle(title) {
                this.title = title
                useDynamicTitle();
            }
        }
    })

export default useSettingsStore

4.utils/dynamicTitle.js   修改标题

import defaultSettings from '@/settings'
import useSettingsStore from '@/store/modules/settings'

/**
 * 动态修改标题
 */
export function useDynamicTitle() {
  const settingsStore = useSettingsStore();
  if (settingsStore.dynamicTitle) {
    document.title = settingsStore.title + ' - ' + defaultSettings.title;
  } else {
    document.title = defaultSettings.title;
  }
}

5.router/permission.js  

vue3/vite 动态路由——动态修改标题(title)_第3张图片

to.meta.title && useSettingsStore().setTitle(to.meta.title)

6.src/settings.js

export default {
  /**
   * 网页标题
   */
  title: 'xxx',

  /**
   * 是否显示动态标题
   */
  dynamicTitle: true,
}

你可能感兴趣的:(vue,vue.js,javascript,前端)