Loading

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 @ 2023-05-24 11:03  DDD-SagerKing  阅读(291)  评论(0编辑  收藏  举报