【问题标题】:Passing data from parent to child via props in v-for in VueJS 2在VueJS 2中通过v-for中的道具将数据从父级传递给子级
【发布时间】:2019-12-16 21:33:50
【问题描述】:

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

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

父.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>

itemsData 通过使用 MapState 从 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",
    }
  ]

【问题讨论】:

  • 您能展示一下您的 itemsData 的样子吗?
  • 如果您可以提供示例 repo,这可能更容易调试。

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


【解决方案1】:

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

父.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>

【讨论】:

  • 请阅读问题。我添加了 mapState
  • mapState 可以进入计算状态,而不是创建状态!
  • 在计算中是的
  • 用你父母的代码更新问题! :)
  • 更新了!请检查
猜你喜欢
  • 2016-11-14
  • 2017-05-15
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多