子组件是根据父组件的数组元素循环遍历生成的。要实现父组件props传参时参数变化时,子组件的对应数据也要变化。子组件和父组件实现“双向绑定”

文章描述了如何在Vue.js中使用TagsInput组件,通过父组件的数组变化驱动子组件的标签列表同步,并演示了如何处理添加、删除和修改操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 <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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值