在 vuejs 中动态绑定标题标签



我是vuejs的新手。

我尝试动态绑定标题标签上的数据。我使用 vue-head 在一个简单的 html 页面上执行此操作。我不使用 webpack 和 npm。

这是我绑定标题标签的方式:

var app = new Vue({
el: 'html',
head: {
title: function () {
return {
inner: this.remaining + ' Tâches',
separator: ' ',
complement: ' '   
}
}
}

在 vue-head 文档中,他们建议这样做:

methods: {
getAsyncData: function () {
var self = this
window.setTimeout(function () {
self.title = 'My async title'
self.$emit('updateHead')
}, 3000)
}
},

我也尝试将其设置在手表道具中,但没有奏效。

这是我的整个代码: https://jsfiddle.net/5d70s0s6/1/

谢谢

使用computed属性。

computed: {
title: {
get() {
document.title = this.remaining
return this.remaining
},
set(val) {
document.title = val
}
}
}

您不需要使用<title>{{title}}</title>.如果您在 Vue 中更改title,它将自动应用于页面。

此外,您不应将 Vue 实例绑定到htmlheadbody标签。只使用像<div id="app"></div>这样的常规元素,并设置你的 Vueel: '#app'

或者你可以使用这个:

data: {
title: '',
},
watch: {
title(val) {
document.title = val
}
}

更新:虽然上面的代码可以解决您的问题。我创建了这个很小的vue-title 组件,可以轻松地在您的项目中使用。

例:

<vue-title>{{title}}</vue-title>

最新更新