<TagsInput ref="tagsInput" :tags.sync="attribute.values"></TagsInput>
TagsInput是封装的子组件
父组件代码使用如下:
TagsInput是根据父组件的数组元素循环遍历生成的。要实现父组件传参时:tags参数变化时,子组件的对应数据也要变化。
// HTML
<a-row :gutter="16" style="margin: 0 0 8px 0;" v-for="(attribute, a) in form.attributeInfos" :key="a">
<a-col class="gutter-row" :span="6">
<a-input :disabled="!attribute.newFlag" v-model.trim="attribute.name"/>
</a-col>
<a-col class="gutter-row" :span="6">
<TagsInput ref="tagsInput" :tags="attribute.values"></TagsInput>
</a-col>
<a-icon type="close-circle" class="i-close-circle" @click="delSpuAttribute(a)"/>
</a-row>
//VUE.js
// 父组件监听参数变化
// this.$nextTick是防止数据在变化时dom元素未生成时 this.$refs.tagsInput[index]报错
watch: {
'form.attributeInfos': {
deep: true,
handler (newValues) {
newValues.forEach((attribute, index) => {
this.$nextTick(() => {
console.log(this.$refs.tagsInput[index].deepTagsAll)
this.$refs.tagsInput[index].deepTagsAll= attribute.values
})
})
}
}
},
子组件
props: {
// 标签tags
tags: {
type: Array,
default: () => {
return []
}
}
},
// deepTagsAll是子组件中接收的拷贝tags参数
// 子组件对参数的各种操作(删除、新增、编辑等)可以使用deepTagsAll
computed: {
deepTagsAll: {
get () {
return this.tags
},
set (value) {
// 在这里可以对 tags 值进行处理,例如去重、排序等
this.$emit('update:tags', value)
}
}
},
methods: {
// 点击叉叉删除tag
removeTag (index, item) {
this.deepTagsAll.splice(index, 1)
}
}
举例:
<PhotoSamplesConfig :configVisible.sync="configVisible"></PhotoSamplesConfig>
// 子组件变更configVisible
handleClose () {
this.$emit('update:configVisible', false)
}
// 变更后父组件的configVisible也会变更为false