首页 > 解决方案 > Vue Nuxtjs 传递道具

问题描述

我得到 id 没有定义,我的道具没有传递给组件,这是索引代码。

id 未定义

<template>
  <div class="home-page">
    <h1>get latest News</h1>
    <post-preview
      id="1"
      thumbnail="https://cdn.pixabay.com/photo/2015/03/26/09/41/chain-690088_1280.jpg"
      previewText="hello first "
      title="test"
    ></post-preview>
  </div>
</template>
<script>
import PostPreview from "../components/posts/PostPreview";

export default {
  components: { PostPreview }
};
</script>

////////////////这是我试图获取道具并使用它的组件。

<template>
  <nuxt-link to="/posts/1">
    <article class="post-preview">
      <div
        class="post-thumbnail"
        :style="{
          backgroundImage: 'url(' + thumbnail + ')'
        }"
      ></div>
      <div class="post-content">
        <h1>{{ title }}</h1>
        <p>{{ previewText }}</p>
      </div>
    </article>
  </nuxt-link>
</template>

<script>
import ref from "vue";
props: [id, title, previewText, thumbnail];
export default {

};
</script>

标签: javascriptnuxt.jsvuejs3

解决方案


您必须propsexport default范围内定义一个组件。 请注意,如果您使用数组来定义组件道具,则应将道具名称定义为string

export default {
  props: ['id', 'title', 'previewText', 'thumbnail'],
...
}

也不要使用,您可以在 Vue 实例方法等ref()中轻松访问您的propswith关键字,也无需在您的thisthistemplate

在您的组件模板范围内

    <div class="post-content">
      <h1>{{ title }}</h1>
      <p>{{ previewText }}</p>
    </div>

或者在组件的实例范围内

  created() {
    console.log(this.title);
  },

推荐阅读