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 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)