乐闻世界logo
搜索文章和话题

How to change page titles when using vue - router ?

1个答案

1

When developing single-page applications with Vue.js and vue-router, it is often necessary to change the page title based on route changes to enhance user experience and SEO optimization. Typically, this can be handled within each route hook or global navigation guard of vue-router.

Method One: Using Route Meta Information (meta fields)

When defining routes, you can specify the title for each route using meta fields, and then set the page title within the route hook.

javascript
const router = new VueRouter({ routes: [ { path: '/', component: Home, meta: { title: 'Home' }}, { path: '/about', component: About, meta: { title: 'About Us' }} ] }); router.beforeEach((to, from, next) => { // Get the title from the meta property of the route to be entered if (to.meta && to.meta.title) { document.title = to.meta.title; } next(); });

This method is intuitive and centralized, making it easy to modify and maintain.

Method Two: Changing the Title Within Components

Besides setting it in the route configuration, you can change the title within specific Vue components. This can be achieved using Vue's lifecycle hooks, such as in mounted() or created() hooks.

javascript
export default { name: 'About', mounted() { document.title = 'About Us'; } }

This method is suitable when the title needs to be dynamically generated or depends on the component's internal state.

Method Three: Creating a Custom Directive

If your project frequently requires changing the title, consider creating a custom Vue directive to simplify the process.

javascript
Vue.directive('title', { inserted: function (el, binding) { document.title = binding.value; } }); // Usage <template> <div v-title="'Home'"></div> </template>

This method makes it very simple to define the title directly in the template.

Summary

To enhance user experience and SEO optimization, setting the page title based on route changes is a common requirement. Through vue-router's global navigation guards, component lifecycle hooks, or custom directives, this can be achieved. In actual projects, you can choose the appropriate method based on your needs.

2024年7月19日 18:06 回复

你的答案