vue设置浏览器title

utils.js代码如下:

export const setTitle = (title) => {
    title = title ? `${title}` : 'demo'
    window.document.title = title
}

store文件,创建user.js,代码如下:

import utils from './utils'; // 引入utils.js的方法
let sessionStorage = window.sessionStorage;

const user = {
    state: {
        browserHeaderTitle: sessionStorage.getItem('browserHeaderTitle') || 'demo'
    },
    getters: {
        browserHeaderTitle: state => state.browserHeaderTitle
    },
    mutations: {
        SET_BROWSERHEADERTITLE: (state, action) => {
            state.browserHeaderTitle = action.browserHeaderTitle
        }
    }
}

export default user;

router.js路由文件,代码如下:

import Vue from 'vue';
import Router from 'vue-router';
import store from './store/user.js'; //引入user.js文件

Vue.use(Router);

const routes = [
    // 路由
    {
        path: '/index',
        component: () =>
            import (// 引入文件),
        meta: {
            title: '首页'
        },
    }
]


const router = new Router({
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { x: 0, y: 0 }
        }
    },
    routes
})


router.beforeEach((to, from, next) => {
    NProgress.start();
    const browserHeaderTitle = to.meta.title;
    store.commit('SET_BROWSERHEADERTITLE', {
        browserHeaderTitle: browserHeaderTitle
    });
    
    next()
})

router.afterEach(() => {
    NProgress.done();
    setTimeout(() => {
        const browserHeaderTitle = store.getters.browserHeaderTitle
        setTitle(browserHeaderTitle)
    }, 0);
})


export default router;

 

你可能感兴趣的:(Vue)