NuxtJS - 将 head title/description 设置为已安装?

NuxtJS - Set head title/description on mounted?

mounted() {
  // threads is a constant file
  this.thread = threads.find(t => t.id === this.$route.params.id)
},
data() {
  return {
    thread: null
  }
},
head: {
  title: this.thread.title,
  meta: [
    {
      hid: 'description',
      name: 'description',
      content: this.thread.body
    }
  ]
},

基本上,我有一个 json "threads" 的常量文件,我想使用它的属性来设置 head - title/description.

我收到这个错误:
无法读取未定义

的 属性 'thread'

你应该在数据方法

中定义thread
data () {
  return {
    thread: {
      body: '',
    }
  }
}

此外,head 应该定义为方法,而不是 属性。

head () {
  return {
    meta: [
      {
        hid: 'description',
        name: 'description',
        content: this.thread.body
      }
    ]
  }
}

aznable 显然你必须从这里删除 null

thread: null => thread: ""

并将其插入到异步方法中

   async getId() {
    this.thread = await threads.find(t => t.id === this.$route.params.id)
   }

最佳!

来自 head documentation,类型是 ObjectFunction

所以如果你重新格式化你的代码,你可以这样写 head

head() {
  const thread = threads.find(t => t.id === this.$route.params.id)

  return {
    title: thread ? thread.title : '',
    meta: [
      {
        hid: 'description',
        name: 'description',
        content: thread ? thread.body : ''
      }
    ]
  }
},