Vue.js Watcher未监听v-model变更问题求助
Vue中编辑待办项无法触发localStorage保存的问题解决
问题出在watch的配置语法错误:你把deep: true写在了watch的根层级,而非todo监听项的配置对象内部,导致深层监听未生效。修改数组内对象的content属性时,Vue无法检测到这个深层变化,自然不会触发localStorage的保存操作。
修正后的代码
重点修正watch部分的写法:
<template> <div class="hello"> <h1>TODO</h1> <input type="text" placeholder="E.g do homework..." v-model="input"> <br> <input type="submit" @click="add()"> <p></p> <div v-for="(item, i) in todo" :key="i"> <input type="text" v-model="item.content" /> </div> </div> </template> <script> export default { name: 'HelloWorld', props: { msg: String }, data(){ return{ todo: [ {content:"welcome", done: false} ], input: "", } }, methods: { add(){ if (!this.input.trim()){ return } this.todo.push({ content: this.input, done: false, }) this.input = "" } }, watch:{ todo: { handler(newVal) { localStorage.setItem("todo",JSON.stringify(newVal)) console.log(localStorage.getItem('todo')) }, deep: true // 正确放置位置:在todo的监听配置对象内 } }, mounted(){ this.todo = JSON.parse(localStorage.getItem('todo')) || [] } } </script>
关键说明
- 深层监听的正确配置:Vue监听数组时,仅当数组执行
push/pop/splice等操作时会触发watch;若要监听数组内对象属性的变化,必须给对应的监听项添加deep: true配置,且该配置需写在监听项的对象内部,而非watch的根层级。 - 额外优化:
add方法里的空值判断可简化为!this.input.trim(),逻辑保持一致且更简洁。
内容的提问来源于stack exchange,提问作者Gebblin
相关产品推荐
相关产品推荐

