【问题标题】:How do you use components with data from Nuxt Content Module如何使用来自 Nuxt 内容模块的数据的组件
【发布时间】:2021-04-30 15:05:57
【问题描述】:

具有隐藏输入字段的组件应该具有当前页面标题的值。在 Nuxt 中,您可以对所有页面使用 asyncData 来完成它,除了使用 Nuxt 内容模块 的页面。 Nuxt 内容模块不允许 asyncData,但允许 fetch。示例:

components/Form.vue

<template>
<div>
  <input
    id="page"
    type="hidden"
    :value="article.title"
    required
  />
</div>
</template>

<script>
export default {
  async fetch() {
    this.article = await this.$content('articles', this.params).fetch()
  },
  data() {
    return { article: {} }
  },
}
</script>

pages/articles/_slug.vue

<template>
<div>
  <h1>{{ article.title }}</h1>
  <Form />
</div>
</template>

<script>
export default {
  async asyncData({ $content, params }) {
    const article = await $content('articles', params.slug).fetch()
    return { article }
  },
}
</script>

此代码没有错误,但组件永远不会在隐藏输入中仅在 h1 标记中显示页面标题。 (编辑:修正错字)

【问题讨论】:

  • 你好。你有解决办法吗?
  • 嗨。是的,我想通了,我现在就提交答案。

标签: vue.js vue-component nuxt.js


【解决方案1】:

我是通过道具解决这个问题的。

components/Form.vue

<template>
    <form>
        <label for="title"> Title </label>
        <input name="title" type="hidden" :value="title" required />
        <button type="submit">Send</button>
    </form>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      required: false,
      default: ''
    },
  }
}
</script>

然后在pages/_slug.vue

<template>
  <div>
    <nuxt-content :document="doc" />
    <Form :title="doc.title" />
  </div>
</template>

这应该适合你。

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2021-06-03
    • 2021-07-14
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2017-01-28
    • 2018-01-22
    相关资源
    最近更新 更多