vue2子组件切换,监听方法失效(监听多个字段)

记录下问题

本来是在父页面上放了多个子组件,利用单选按钮控制每个组件,选择了某个按钮,设置该组件控制字段为true,例如v-if="component"来控制销毁创建,根据component=true或者flase来控制子组件创建或者销毁

后来发现子组件切换时,监听不生效,监听方法也加了immediate=true,当几个按钮用的是同一个组件时,第二次还选择该组件,才会触发监听方法

经排查是监听多个字段的方法写的有问题

原来写的是

复制代码
watch: {
            componentStr:
                function (newVal, oldVal) {
                    this.componentDictType = newVal;
                    console.log("newComponentDictType:" + newVal + ",oldComponentDictType:" + oldVal);
                    if (newVal != null) {
                        this.getTypeList(newVal);
                    }
                },
            componentHeader:
                function (newVal, oldVal) {
                    this.componentHeaderString = newVal;
                    console.log("newcomponentHeaderString:" + newVal + ",oldcomponentHeaderString:" + oldVal);
                    if (newVal != "") {
                        this.setHeaderString(newVal);
                    }
                },
           immediate: true
}
复制代码

这种写法是错误的,改成了

复制代码
watch: {
            componentStr: {
                handler: function (newVal, oldVal) {
                    this.componentDictType = newVal;
                    console.log("newComponentDictType:" + newVal + ",oldComponentDictType:" + oldVal);
                    if (newVal != null) {
                        this.getTypeList(newVal);
                    } 
                },
                immediate:true
            },
            componentHeader: {
                handler:function(newVal, oldVal) {
                    this.componentHeaderString = newVal;
                    console.log("newcomponentHeaderString:" + newVal + ",oldcomponentHeaderString:" + oldVal);
                    if (newVal != "") {
                        this.setHeaderString(newVal);
                    }
                },
                immediate:true
            }
}
复制代码

 

posted @   DDD-SagerKing  阅读(379)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示
主题色彩