gpt4 book ai didi

javascript - 在 Nuxt.Js 中为 document.title 添加一个观察者

转载 作者:行者123 更新时间:2023-12-01 15:46:05 24 4
gpt4 key购买 nike

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

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

共同组件:

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

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

有什么方法可以访问 this.$router 中的元标题, this.$meta或者可以看 document.title每当 URL 更改时?

谢谢!

最佳答案

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>

关于javascript - 在 Nuxt.Js 中为 document.title 添加一个观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57287500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com