首页 > 解决方案 > 如何将绑定集合发送给子集合并允许本地操作而不改变父集合?

问题描述

如何向孩子发送项目列表,允许孩子在内部选择/取消选择而不影响源列表?

家长

          <div class="col-sm-10">
            <check-list :items="localObjs"
                        text-property="name"
                        value-property="id" />
          </div>

孩子

<template>
  <div class="form-control item-container">
    <div class="custom-control custom-checkbox mr-sm-2" v-for="item in items">
      <input type="checkbox"
             class="custom-control-input"
             :id="item[valueProperty]"
             v-model="item.isSelected">

      <label class="custom-control-label"
             :for="item[valueProperty]">{{item[textProperty]}}</label>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'CheckList',
    props: {
      items: Array,
      valueProperty: String,
      textProperty: String
    },
    methods: {

    },
    computed: {

    }
  };
</script>

我尝试过从父级绑定到子级,但这会改变父列表。我也尝试过创建一个本地副本,如下所示:

created: function () {
  this.localItems = this.items.slice();
},

并且使用它但它不起作用,没有任何内容被复制。可能是因为它在items集合设置之前尝试复制。

我想在每次父级更新时更新子级列表,但将复选框选择保留在子级本地并且不影响父级的选择。

标签: javascriptvue.js

解决方案


您应该在数据函数中返回项目并重命名道具项目属性。然后,看道具:

<script>
  export default {
    name: 'CheckList',
    props: {
      prarentItems: Array, // rename
      valueProperty: String,
      textProperty: String
    },
    data(){
      return { items: [] } // local state
    },
    methods: {

    },
    computed: {

    },
    watch:{
      prarentItems(newValue, oldValue){ // watch prop attribute
        this.items = newValue.map(v => {...v}); // on change, update local state cloning values
      }
    }
  };
</script>

推荐阅读