将对象传递给组件

时间:2019-01-07 19:56:00

标签: vue.js

在我的父母中,我有一个数组items和一个索引selected指向所选项目。

 data() {
    return {
      items: [
          {id: 100, acronym: 'ABC', description: ''},
          {id: 200, acronym: 'DEF', description: ''},
          {id: 300, acronym: 'GHI', description: ''},
      ],
      selected: 0
    }
  }

还有一个组件item-editor用于显示该项目并允许进行编辑:

<script>
    export default {
        props: ['item']
    }
</script>

<template>
    <v-card>
      <v-card-text>
            <v-text-field label="Acronym" v-model="item.acronym" />
            <v-text-field label="Description" v-model="item.description" />
      </v-card-text>
    </v-card>
</template>

<style scoped>
</style>

然后我如何将项目item[selected]传递给此组件,以便该组件写回相同的内容?

例如像这样的东西:

<item-editor ???="items[selected]" />

2 个答案:

答案 0 :(得分:1)

您的???必须为:item,如下所示:

<item-editor :item="items[selected]" />

就是这样!

答案 1 :(得分:0)

一种方法是通过自定义事件发送数据备份。

在孩子中:

export default {
  props: ['item'],
  data() {
    return {
      myitem: ''
    };
  },
  methods: {
    childChanged () {
      // childChanged is your method of updating this items values
      this.$emit('mymethod', this.myitem); // emit to parent
    }
  },
  mounted(){
     this.myitem = this.item; // assign props to self
  }
}

在父级中捕获正在发出的事件

<child-component @mymethod="updateItems"></child-component>

,然后在方法中:

  methods: {
    updateItems(data){
      this.items[selected] = data;
    }
  }
相关问题