【问题标题】:Add a watcher to document.title in Nuxt.Js在 Nuxt.Js 中为 document.title 添加一个观察者
【发布时间】:2019-07-31 09:27:05
【问题描述】:

我正在使用 nuxt.js 并为不同的页面添加了不同的标题。

所有页面中都出现了一个组件,我想在那里访问document.title

通用组件:

console.log(document.title) // Always comes the same one when the page loaded

当我改变路线时,我想在那里获得新的标题。

我有什么方法可以访问this.$routerthis.$meta 中的元标题,或者可以在 URL 更改时观看document.title

谢谢!

【问题讨论】:

    标签: javascript vue.js single-page-application nuxt.js


    【解决方案1】:

    Nuxt.js @ v2.13.1

    目前无法通过 $router 对象监听标题更新。

    工作变体https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

    您需要订阅更新 DOM 元素。

    在主布局中:

    <template>
      <h1>{{ title }}</h1>
    </template>
    
    <script>
    export default {
      data: () => ({
        title: null
      }),
      // or created() hook, if it's not SSR
      mounted() {
        this.title = document.title
        new MutationObserver(() => {
          this.title = document.title
        }).observe(document.querySelector('title'), { childList: true })
      }
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 2013-03-08
      • 1970-01-01
      • 2012-12-10
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      相关资源
      最近更新 更多