vue watch监听为什么第二次不会触发?

比如编辑功能。点击编辑按钮,在父组件向子组件传递一个值,字符串或对象,在子组件中使用watch监听,在modal弹窗表单里显示。

情况描述:第一次能够正常显示,点击关闭取消表单后,再次点击编辑按钮,打开弹窗,此时子组件的watch监听不能触发,为什么?

父组件代码片断:

<col span="4">

<button

type="primary"

@click="addItem(item.plantPartName)"

>新增</button>

</col>

    <addParts

ref="addParts"

:currentPlantPartName="currentPlantPartName"

:isShow="isShow"

></addParts>

    addItem(plantPartName) {

this.isShow = true

this.currentPlantPartName = plantPartName

},

子组件监听:

    currentPlantPartName: {

handler(newName, oldName) {

this.model.plantPartName = newName

console.log('子组件收到名称:', newName)

},

deep: true

},


回答:

watch 只会在监听的属性发生变化时触发。根据你的描述,问题可能是你在点击编辑按钮时未更改传递给子组件的值。导致 watch 不会触发,因为值没有实际变化。你想要解决这个问题的一个方法是确保每次点击编辑按钮时都更新传递给子组件的值。

要解决这个问题,你可以使用一个简单的技巧:在每次传递值给子组件之前,先将其设置为一个不同的值。例如,你可以将其设置为null,然后再设置回你想要传递的值。这样,每次点击编辑按钮时,Vue 将检测到currentPlantPartName的变化并触发子组件的watcher。

在父组件的addItem方法中,你可以试以下操作:

addItem(plantPartName) {

// 将值设置为 null 以触发 watcher

this.currentPlantPartName = null;

// 使用 $nextTick 确保在下一个 DOM 更新周期再设置正确的值

this.$nextTick(() => {

this.currentPlantPartName = plantPartName;

});

this.isShow = true;

},


回答:

vue watch监听为什么第二次不会触发?
其实不需要深度监听
红框的用$set写一下this.$set(this.model, 'plantPartName',newName )

以上是 vue watch监听为什么第二次不会触发? 的全部内容, 来源链接: utcz.com/p/934044.html

回到顶部