【问题标题】:Vue Nuxtjs passing propsVue Nuxtjs 传递道具
【发布时间】:2021-06-18 21:40:23
【问题描述】:

i get id is not defined ,我的 props 没有传递给组件,这里是索引代码。

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>

【问题讨论】:

    标签: javascript nuxt.js vuejs3


    【解决方案1】:

    您必须在export default 范围内定义一个组件props注意,如果您使用数组来定义组件道具,您应该将道具名称定义为string

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

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

    在您的组件模板范围内

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

    或者在组件的实例范围内

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

    【讨论】:

      【解决方案2】:

      尝试另一种方式来初始化组件,如下所示:

      <template>
        <button>{{item.name}}</button>
      </template>
      <script>
        export default {
          name: "my-item",
          props: {
            item: Object,
          },
        };
      </script>
      
      ...
      
      <template>
        <MyItem :item="item" />
      </template>
      <script>
        export default {
          components: { MyItem },
        };
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-10
        • 2018-05-29
        • 2020-10-19
        • 2020-08-28
        • 2020-04-04
        • 1970-01-01
        • 2020-05-04
        • 2019-01-15
        相关资源
        最近更新 更多