道具不变怎么看? [英] How to watch prop even if it does not change?

查看:50
本文介绍了道具不变怎么看?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与道具同名的观察者.prop 是在某个事件的父组件中动态设置的.每次在父组件上触发事件时,我都需要使用属性值触发子组件中的某些功能 - 即使它设置的道具相同.是否有任何观察者选项或其他处理这种情况的方法可以让我这样做?

I have watcher with the same name as a prop. The prop is dynamically set in a parent component on some event. I need something that triggers some function in the child component with property value every time the event is triggered on parent -even if the prop it set is the same. Is there any watcher option or other method of handling such case which would allow me to do that ?

我尝试过的(这是在 Post 组件中):

What I tried (this is in Post component):

watch: {
    replyClicked:
    {
        handler(newVal, oldVal)
        {
            console.log(newVal, oldVal);
        },
        immediate:true
    }
},

console.log 仅在 newVal 与 oldVal 不同时才打印,即使它们相同,我也需要一些函数来触发.父组件如下所示:

the console.log only prints when newVal is different from oldVal, I need some function to trigger even if they are the same. The parent component looks like this:

<RenderPost @onReply="onReply" />
<Post :replyClicked="replyClicked" />

这些是父数据和方法:

data()
{
    return {
        replyClicked : null
    }
},
methods :
{
    onReply(id)
    {
        this.replyClicked = id;
    }
}

推荐答案

您可以使用 immediate 选项:

watch:{
  yourProp:{
   handler(newval,oldVal){

   },
   immediate:true,
   deep:true //if the prop is an object or an array

 }

}

编辑

由于旧值与新值相同,您可以尝试此解决方法,通过添加始终更改的字段将道具定义为对象:

since the old value is the same as the new one, you could try this workaround, by defining the prop as an object by adding a field that always changes :

data()
{
    return {
        replyClicked : {
          changeCount:0,
          id:null
         }
    }
},
methods :
{
    onReply(id)
    {
        this.replyClicked ={id, changeCount:this.replyClicked.changeCount+1}
    }
}

子组件:

watch: {
    replyClicked:
    {
        handler(newVal, oldVal)
        {
            console.log(newVal, oldVal);
        },
        immediate:true,
        deep:true
    }
},

这篇关于道具不变怎么看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆