Method Example of vue Dynamic Setup Page title
- 2021-08-09 06:43:51
- OfStack
This paper mainly introduces the method of dynamically modifying title by Vue. Friends who need it can refer to it. The method is as follows:
1. Modify through custom instructions (single modification is better)
//1. In main.js Add custom instructions to the page
Vue.directive('title', {// Single Modified Title
inserted: function (el, binding) {
document.title = el.dataset.title
}
})
//2. Add to the page that needs to be modified v-title Instruction
<div v-title data-title=" I am the new title "></div>.
2. Use the plug-ins vue-wechat-title
//1. Install plug-ins
npm vue-wechat-title --save
//2. In main.js Introduce plug-ins inside
import VueWechatTitle from 'vue-wechat-title'// Dynamic modification title
Vue.use(VueWechatTitle)
//3. Inside the route Add title
routes: [{
path: '/login',
component: Login,
meta: {
title: ' Login '
}
}, {
path: '/home',
component: Home,
meta: {
title: ' Home page '
}
},]
//4. In app.vue Add to Instruction v-wechat-title
<router-view v-wechat-title='$route.meta.title' />
3. Modified by router. beforeEach Navigation Guard
//1. In router Adj. index Write your own path and title
const router = new Router({
routes: [
{
path: '/login',
component: Login,
meta: {
title: ' Login ',
},
},
{
path: '/home',
component: Home,
meta: {
title: ' Home page ',
},
},
],
})
//2. Use router.beforeEach Traverse the route and set the title
router.beforeEach((to, from, next) => {
//beforeEach Yes router Before entering the route, execute the hook function of
if (to.meta.title) {
// Determine if there is a title
console.log(to.meta.title)
document.title = to.meta.title
} else {
document.title = ' Default title'
}
next()
})
4. Modify title with vue-mate
The https://github. com/declandewet/vue-meta document explains in more detail how to use vue-meta to modify page header information on the browser side and the server side
Summarize