【问题标题】:NuxtJS - Set head title/description on mounted?NuxtJS - 在安装时设置头部标题/描述?
【发布时间】:2019-06-12 11:27:47
【问题描述】:
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“线程”的常量文件,我想使用它的属性来设置标题 - 标题/描述。

我收到此错误:
无法读取未定义的属性“线程”

【问题讨论】:

标签: vue.js nuxt.js


【解决方案1】:

你应该在数据方法中定义thread

data () {
  return {
    thread: {
      body: '',
    }
  }
}

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

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

【讨论】:

  • 头部应该定义为函数,返回值类似于数据函数。 ``` head () { return { meta: [ {hid: 'description'} ]} }```
【解决方案2】:

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 : ''
      }
    ]
  }
},

【讨论】:

  • 我现在无法测试这个,如果有帮助请告诉我:)
  • 哦.. 它有效,但仅用于描述。标题没有改变(nuxt 仍然显示在 nuxt.config 中定义的默认标题
  • 我删除了 nuxt 配置上的标题模板,它工作正常。谢谢!
【解决方案3】:

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

thread: null => thread: ""

并将其插入异步方法中

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

最好的!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2021-10-10
    • 2020-09-12
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多