VUE2.x-setting page jump page title change (Vue Router+Vue Meta)

If you want the page title to change as the page jumps, you can use the Vue Router and Vue Meta plugins to achieve it.

Vue Meta is a Vue.js plugin that allows you to dynamically set metadata such as page title, description, keywords, etc. in each page.

The following is an example that demonstrates how to use Vue Router and Vue Meta to dynamically change the page title:

  1. Anso Vue Meta:
npm install vue-meta
  1. main.jsConfigure Vue Meta and Vue Router in :
import Vue from 'vue';
import VueMeta from 'vue-meta';
import App from './App.vue';
import router from './router';

Vue.use(VueMeta);

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');
  1. In the route configuration file (usually router.js), define a field for each route metaand store the page title in meta.titlethe :
import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '@/views/index.vue'
import About from '@/views/About.vue'
import Login from '@/views/login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/index',
    name: 'Index',
    component: Index,
	meta: {
	  title: '首页'
	}
  },
  {
    path: '/about',
    name: 'About',
    component: About,
	meta: {
	  title: '关于'
	}
  },
  {
    path: '/',
    name: 'Login',
    component: Login,
	meta: {
	  title: '登录'
	}
  }
]

const router = new VueRouter({
  routes
})

export default router

In the above example, we added a metafield to each route configuration to store the title of the page.

  1. App.vueUse the Vue Meta object in the root component (usually ) $metaInfoto set the title of the page:
<template>
  <div>
    <h1>My Vue App</h1>
    <router-link to="/">Login</router-link>
    <router-link to="/index">Index</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  metaInfo() {
    return {
      title: this.$route.meta.title || 'My Vue App'
    };
  }
};
</script>

In the above example, we use metaInfothe method to dynamically set the title of the page. metaSet the title of the page according to the property in the field of the current route title, or use the default title if not defined 'My Vue App'.

Through the above steps, when you jump to a different page, the title of the page will be changed to the title of the corresponding page accordingly. Make sure you set the correct title for each page in your routing configuration, and use the Vue Meta $metaInfoobject in the root component to dynamically set the page's title.

Guess you like

Origin blog.csdn.net/m0_52177571/article/details/131519930