Vue watch 死循环

我想监听ruleForm对象的moduleDir属性,根据属性值得变化,修改ruleForm对象的另一个属性genModules。但发生了死循环。代码如下:

watch: {
    ruleForm: {
        handler(newVal) {
            console.log(this);
            //以下代码造成死循环
            if ('/common' === newVal.moduleDir) {
                this.ruleForm.genModules = ["modelAndMapper", "repository", "service"];
            } else if ('/api' === newVal.moduleDir) {
                this.ruleForm.genModules = ["controller"];
            } else if ('/web' === newVal.moduleDir) {
                this.ruleForm.genModules = ["controllerAndPage"];
            }
        },
        deep: true,
        immediate: true
    }
}
阅读 8.9k
6 个回答

因为你修改了genModules,意味着ruleForm也变了,
试试能不能单独监听这个属性

watch:{
'ruleForm.moduleDir':function(val){
console.log(val)
}
},

你也说了要见监听 ruleForm 的 moduleDir, 那为什么代码里要监听整个 ruleForm 呢?

watch: {
    'ruleForm.moduleDir': { }
}

还是在computed里把moduleDir拿出来然后监听这个计算出来的变量吧。。

computed: {
  moduleDir(){
    return this.ruleForm.moduleDir
  }
},
watch: {
  moduleDir(newValue, oldValue){
    //do something
  }
}

判断一下数组是否和你想要赋值的数组是否相等:

watch: {
    ruleForm: {
        handler(newVal) {
            console.log(this);
            //以下代码造成死循环
            let list = []
            if ('/common' === newVal.moduleDir) {
                list = ["modelAndMapper", "repository", "service"];
            } else if ('/api' === newVal.moduleDir) {
                list = ["controller"];
            } else if ('/web' === newVal.moduleDir) {
                list = ["controllerAndPage"];
            }
            let oldList = this.ruleForm.genModules
            // 判断新旧数组一致则直接返回
            if (list.length == oldList.length && list.every((item, idx) => oldList[idx] == item)) return
            this.ruleForm.genModules = list
        },
        deep: true,
        immediate: true
    }
}

不使用watch,使用v-on:change或@change。

v-on:change="changeGenModules(ruleForm.moduleDir)"

methods: {
    changeGenModules(moduleDir) {
        if ('/common' === moduleDir) {
            this.ruleForm.genModules = ["modelAndMapper", "repository", "service"];
        } else if ('/api' === moduleDir) {
            this.ruleForm.genModules = ["controller"];
        } else if ('/web' === moduleDir) {
            this.ruleForm.genModules = ["controllerAndPage"];
        }
    },
}

同一楼解决方法

computed: {
    moduleDir () {
        return this.ruleForm.moduleDir
    }
},
watch: {
    moduleDir (newDir, oldDir) {
        // 做些其他事情,如修改ruleForm对象的另一个属性genModules
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题