简体   繁体   English

如何根据不断变化的道具渲染 v-for?

[英]How to render a v-for based on changing props?

Maybe I have a missconcept based on React.js, but I am working wih Vue.js也许我有一个基于 React.js 的错误概念,但我正在使用 Vue.js

I Just create a component:我只是创建一个组件:

<ResultCards v-bind:cards="cards"/>

cards is updated when an event is triggered by other component:当其他组件触发事件时更新cards

  methods: {
    fillResultCards(cards){
      this.cards = cards;
    }
  }

This is my ResultCard Component这是我的ResultCard组件

<template>
  <div>
    <v-card
      v-for="card in cards"
      v-bind:key="card.id"
    >
     // ..card detail here
    </v-card>
  </div>

</template>

<script>
  export default {
    name: 'ResultCards.vue',
    props: {
      cards: Array,
    },
  };
</script>

But when I update the "cards" props send me the message:但是当我更新“卡片”道具时,会向我发送消息:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "cards"

I tried to copy cards prop to a internal dat我试图将cards道具复制到内部数据

  data() {
    return { internalCards: this.cards };
  }

but it doesn't works.但它不起作用。

Okay, it works, maibe I had a typo, but this is the FULL flow.好的,它有效,也许我有一个错字,但这是完整的流程。

I have external Component (a search bar)我有外部组件(搜索栏)

<SearchGit v-on:item-selected="fillResultCards"/>

when search concept fill the input, it emit the event item-selected passing results (from API) as args.当搜索概念填充输入时,它会发出事件item-selected传递结果(来自 API)作为 args。 this.$emit('item-selected', this.cache.filter(item => item.full_name === textSearch));

In Container I set my data with the function在容器中,我使用 function 设置我的数据

  data: () => ({
    cards: [],
  }),
  methods: {
    fillResultCards(cards){
      this.cards = cards;
    }
  }

then this "new version" of cards pass as prop to the render component然后这个“新版本”的cards作为道具传递给渲染组件

<ResultCards v-bind:cards="cards"/>

And the render component only need to render data, and thats all:而渲染组件只需要渲染数据,仅此而已:

 <v-card
      v-for="card in cards"
      v-bind:key="card.id"
    >
      <v-list-item three-line>
        <v-list-item-content>
          <div class="overline mb-4">{{ card.name }}</div>
          <v-list-item-title class="headline mb-1">{{
            card.full_name
          }}</v-list-item-title>
          <v-list-item-subtitle>{{ card.description }}</v-list-item-subtitle>
        </v-list-item-content>

        <v-list-item-avatar tile size="80" color="grey">
          <img v-bind:src="card.owner.avatar_url" alt="avatar" />
        </v-list-item-avatar>
      </v-list-item>
    </v-card>

I don't change any of the code, but maybe a cache or something keeps old changes, it works now.我没有更改任何代码,但也许缓存或其他东西保留了旧的更改,它现在可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM