VUE動態修改titile的三種方法


第一種:適用於在已經定義好title的情況下,例如首頁,關於頁等等

1.1 main.js

const defaultTitle = '默認 title'
router.beforeEach((to, from, next) => {
 document.title = to.meta.title ? to.meta.title : defaultTitle
 next()
})

 

1.2 index.js

routes: [
    {
        name:'home',
          path: '/home/:openname',
          component: Home,
          meta: {
            title: '首頁'
        }
    }
  ]

 

 

第二種:vue-meta 插件(適用於無法固定title的情況下,例如文章頁)

vue-meta官網文檔看這里

2.1 安裝

npm install vue-meta --save

 

2.2 在main.js引入

import Meta from 'vue-meta'
Vue.use(Meta)

 

2.3 為需要修改的頁面單獨定義metaInfo

export default {
    metaInfo: {
      title: 'This is the test',
      meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes' }
      ]
    }
}

 

2.4 異步請求數據可以使用

如果component中使用了異步請求數據,可以使用 metaInfo() 方法。

<template>
  <div>
    <h1>{{{ title }}}</h1>
  </div>
</template>

<script>
  export default {
    name: 'post',
    data () {
      return {
        title: ''
        description: '這是一篇文章...'
      }
    },
    metaInfo () {
      return {
        title: this.title,
        meta: [
          { vmid: 'description', name: 'description', content: this.description }
        ]
      }
    },
    created () {
      this.initData()
    },
    methods: {
      initData () {
        axios.get('some/url').then((resp) => {
          // 設置title時 metaInfo 會同時更新
          this.title = resp.title
          this.description = resp.decription
        })
      }
    }
  }
</script>

 

 

第三種:vue-wechat-title

3.1 安裝

npm install vue-wechat-title --save

 

3.2 在main.js中引入

import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)

 

3.3 使用

在router>index.js中添加meta對象配置title

const router = new Router({
 
  routes: [
    ...
    {
      path: "/gameDesc", 
      name: 'gameDesc',
      component: resolve => import('@/pages/Game/gameDesc'),
      meta:{
        title: '游戲說明'
      }
    },
    {
      path: "/integralList", 
      name: 'integralList',
      component: resolve => import('@/pages/Game/integralList'),
      meta:{
        title: '積分收取記錄'
      }
    }
    ...
 
 ]
});
 
router.afterEach(route => {
  // 從路由的元信息中獲取 title 屬性
  if (route.meta.title) {
    document.title = route.meta.title;
    // 如果是 iOS 設備,則使用如下 hack 的寫法實現頁面標題的更新
    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      const hackIframe = document.createElement('iframe');
      hackIframe.style.display = 'none';
      hackIframe.src = '/static/html/fixIosTitle.html?r=' + Math.random();
      document.body.appendChild(hackIframe);
      setTimeout(_ => {
        document.body.removeChild(hackIframe)
      }, 300)
    }
  }
});
 
export default router;

  

在App.vue中修改router-view

<router-view v-wechat-title='$route.meta.title'></router-view>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM