在VueJS 2中通过v-for中的道具将数据从父母传递给孩子

时间:2019-08-09 07:08:32

标签: javascript vue.js vuejs2 vue-component vuex

我遇到了类似的问题,但是我找不到答案,没有一个对我有用。

Vuejs v-for Passing data Parent to Child

Vue - Passing parent data with same key name in v-for to child component

vue js how to pass data from parent, v-for loop list to child component with method

Pass data object from parent to child component

Vue.js - Pass in Multiple Props to Child in V-For

VUE / VUEX: How To Pass Data From Parent Template To Child Template

Parent.vue

            <div class="col-sm-2" v-for="(item,index) in itemsData" :key="index">
              <ItemWidget :item="item" />
            </div>

<script>
import { mapState, mapActions } from "vuex";

import ItemWidget from "@/components/item/ItemWidget";

export default {
  components: { ItemWidget },
  computed: {
    ...mapState("item", ["itemsData"])
  },
  created() {
    this.getItemList();
  },

  methods: {
    ...mapActions("item", ["getItemListX"]),
    getItemList() {
      this.getItemListX();
    }
  }
};
</script>

ItemWidget.vue

<template>
    <div class="label">
      <div class="label-value">{{ item.code }}</div>
    </div>
</template>

<script>
export default {
  props: ["item"]
};
</script>
通过使用MapState将

itemsData从vuex中获取到父对象,并通过vuex中的axios调用在父对象中使用created()方法填充itemsData。

错误1。

[Vue warn]: Error in render: "TypeError: _vm.item is undefined"

错误2。

TypeError: "_vm.item is undefined"

我该如何解决?

更新

  itemsData: [
    {
      code: "Test",
    }
  ]

1 个答案:

答案 0 :(得分:0)

您应该使用... mapState在计算方法中填充itemsData

Parent.vue

export default {
  data: function () {
    return {
      items: this.itemsData
    }
  },
  computed:{
    ...mapState('module/namespace', ['itemsData'])
  }

}

<div class="col-sm-2" v-for="(item,index) in items" :key="index">
    <ItemWidget :item="item" />
</div>

还有另一种声明道具的方法:

<template>
    <div class="label">
      <div class="label-value">{{ item.code }}</div>
    </div>
</template>

<script>
export default {
  props: {
    type: Object,
    default: null
  }
};
</script>