Vue 动态设置页面的标题title

公司的管理后台用vue+elementUI构建的,所有的路由都是通过vue-router来管理的,所有的页面的路径、title、name等属性都是在改路由下配置好的,然后通过路由守卫afterEach方法在页面跳转完成后设置既定好的title属性给当前页面

router.afterEach(to => {
  NProgress.done()

  document.documentElement.scrollTop = 0
  if (to.meta && to.meta.title) {    
    setTitle(to.meta.title)
  }
})

const setTitle = titleText => {
  const processTitle = process.env.VUE_APP_TITLE || 'xxx'
  window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}

这样可以给既定的已经配置好的路由设置title属性,但是如果我同一个页面根据不同状态可能会有多种title的情况下,重新给page设置一个title属性,试过了很多种方法都不生效,最后用到了操作dom节点的方法才解决了这个问题 通过querySelector找到对应的节点,然后重新给该标题赋值

  created() {
    /// 主动设置标题
    this.$nextTick(() => {
      document.querySelector('.tags-li.active .kz-input-fit span').innerHTML = this.state === 1 ? '特批服务站专属白条' : '新增服务站专属白条'
    })
  }

另外一种方式 在tag初始化的时候设置bus监听,然后通过bus把要修改的传递给tag赋值
引用vTag

<v-tags :class="{ 'content-collapse': collapse }"></v-tags>

vTag中create的时候通过bus监听字符串"change-title"

created() {
  /// 动态设置页面标题
  bus.$on('change-title', (urlPath, title) => {
    let _tagIndex = -1
    let tmpItem
    this.tagsList.map((item, index) => {
      if (item.fullPath.indexOf(urlPath) > -1) {
        _tagIndex = index
        tmpItem = item
      }
    })
    if (tmpItem) {
      /// 设置标题
      this.$set(tmpItem, 'title', title)
    }
  })
}

使用:在需要动态修改标题的地方 bus.$emit发消息动态设置页面在tag中的显示标题

bus.$emit(
  'change-title',
  this.$route.fullPath,
   this.state === 1 ? '特批服务站专属白条' : '新增服务站专属白条'
)
posted @ 2022-07-21 10:06  qqcc1388  阅读(3013)  评论(0编辑  收藏  举报