详解Vue Elementui中的Tag与页面其它元素相互交互的两三事

2020-06-14 06:18:18易采站长站整理

},
detailData: [],
checkBox: [{
name: '小红',
id: '101'
},
{
name: '小黄',
id: '100'

}, {
name: '小明',
id: '102'

}, {
name: '小明',
id: '102'

}
],

}
},
methods: {
clearAll() { //全部清空数据
this.tags = [] this.tempForm.checkboxGroup5 = [] },
perChange(item) {
this.detailData.push(item)
},
handleClose(tag) { //标签的删除事件
// 去掉当前删除的tag
let yourChoseTags = this.tempForm.checkboxGroup5

this.tempForm.checkboxGroup5 = yourChoseTags.filter(item => {
if (tag.id !== item) {
return true
}
})

},
delRepeat(arr) { //数组对象去重
return Object.values(
arr.reduce((obj, next) => {
var key = JSON.stringify(next);
return (obj[key] = next), obj;
}, {}),
);
},
moreArr() {
let yourChose = this.tempForm.checkboxGroup5
let tempTags = []

tempTags = this.baseDataDetail(yourChose, this.checkBox, tempTags)
this.detailData = tempTags
},
baseDataDetail(yourChose, baseData, callBack) { //封装的数组方法
let temp = callBack
// 循环两个数据拿到选择的checkbox的id对应的初始数据
yourChose.forEach(item => {
baseData.forEach(itemSecond => {
if (item === itemSecond.id) {
temp.push(itemSecond)
}
})
})
return temp
},

},
watch: {
detailData() {
let tempArr = Object.assign([], this.detailData)
tempArr = this.delRepeat(tempArr)
// console.log(tempArr)
this.tags = tempArr
},
"tempForm.checkboxGroup5" () {
this.moreArr()
},
}
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.tempArea {
/*width: 100%;*/
}
.tagClass{
margin-right: 10px;
}

</style>

值得注意的点:

1.我在多选框绑定值tempForm.checkboxGroup5的监听事件里的方法的最后,得到了一个可能会有重复数据(重复id跟name),再将这个含有重复数据数组对象赋值给另一个数组detailData,在watch监听这个数组,去完重后,赋值给tags做展示。
为什么这样做,是因为,我们的需求里,除了在当前页面多选框选择人员,还有一个选择全公司员工的组件,这样不管从哪个渠道选择的人员都能最后将结果指向detailData,保证渲染正确

2.数组对象去重,初始数据里可能会有重id、重名的对象(小明),即便绑定多选框的model值里不会有重复的id,但在 利用id取对应name的时候,还是会检测出多条,这样tag就可能会显示重复的
所以利用这个方法,就能保证最后处理好的数据没有重复的,tag不会显示多个一样的,