[英]Add a watcher to document.title in Nuxt.Js
我正在使用 nuxt.js 并为不同的页面添加了不同的标题。
有一个组件出现在所有页面中,我想在那里访问document.title
。
在公共组件中:
console.log(document.title) // Always comes the same one when the page loaded
当我改变路线时,我想在那里获得新标题。
有什么方法可以访问this.$router
、 this.$meta
的元标题,或者可以在 URL 更改时观看document.title
吗?
谢谢!
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.