javascript - 如何将绑定集合发送给子集合并允许本地操作而不改变父集合?
问题描述
如何向孩子发送项目列表,允许孩子在内部选择/取消选择而不影响源列表?
家长
<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
集合设置之前尝试复制。
我想在每次父级更新时更新子级列表,但将复选框选择保留在子级本地并且不影响父级的选择。
解决方案
您应该在数据函数中返回项目并重命名道具项目属性。然后,看道具:
<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>
推荐阅读
- javascript - 如何从外部将键名从 ViewBag 传递给 JQuery
- ios - 收据数据验证信息未提供
- javascript - 正则表达式模式重复
- css - IONIC Card 布局样式似乎不居中且不等间距
- ios - 观察 NSUserDefaults 设置值
- r - 自动安装二进制包的依赖
- c# - .net 核心发送 ClaimsPrincipal 作为操作的响应
- arrays - 在相等检查后更改索引值 wrt 数组的最大值
- spring - 带有 Spring 的嵌入式 Tomcat 抛出 IllegalAccessError:
无法访问其超接口 - python - 从文本文件创建嵌套字典