更新复选框列表时 Vuejs 的奇怪行为
Vuejs strange behavior when a list of checkboxes are updated
嗯,不好解释。
我有一个 复选框列表 从 反应数据 生成。当您选中其中一个复选框时,将删除反应数据的条目之一。
然后更新列表。
然后将下一个复选框 置于鼠标光标下方,并通过释放鼠标按钮“激活”。这种行为是不受欢迎的,您能找到避免这种情况的方法吗?
下面是说明这种情况的代码:
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="todo in todos">
<label>
<input type="checkbox"
v-on:change="toggle">
{{ todo.text }}
</label>
</li>
</ol>
</div>
脚本部分:
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript" },
{ text: "Learn Vue" },
{ text: "Play around in JSFiddle" },
{ text: "Build something awesome" }
]
},
methods: {
toggle: function(){
this.todos.splice(1,1)
}
}
})
也是现场测试:https://jsfiddle.net/m10jyLut/7/
不知道我的设计是否正确。我想避免过于陈腐的解决方案。
非常感谢您的猜测。
我在 v-for 中添加了“key”,这总是一个好主意,并通过 toggle() 传递 todo.id。
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="todo in todos" :key="todo.id">
<label>
<input type="checkbox"
v-on:change="toggle(todo.id)">
{{ todo.text }}
</label>
</li>
</ol>
</div>
你的脚本标签应该是这样的:
new Vue({
el: "#app",
data: {
todos: [
{ id: Math.random() * 100000, text: "Learn JavaScript", },
{ id: Math.random() * 100000, text: "Learn Vue", },
{ id: Math.random() * 100000, text: "Play around in JSFiddle", },
{ id: Math.random() * 100000, text: "Build something awesome", }
]
},
methods: {
toggle(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
}
}
})
在 Vue.js 中,将 key 添加到 v-for 并使用 ids 进行渲染操作总是一个好主意。
嗯,不好解释。
我有一个 复选框列表 从 反应数据 生成。当您选中其中一个复选框时,将删除反应数据的条目之一。
然后更新列表。
然后将下一个复选框 置于鼠标光标下方,并通过释放鼠标按钮“激活”。这种行为是不受欢迎的,您能找到避免这种情况的方法吗?
下面是说明这种情况的代码:
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="todo in todos">
<label>
<input type="checkbox"
v-on:change="toggle">
{{ todo.text }}
</label>
</li>
</ol>
</div>
脚本部分:
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript" },
{ text: "Learn Vue" },
{ text: "Play around in JSFiddle" },
{ text: "Build something awesome" }
]
},
methods: {
toggle: function(){
this.todos.splice(1,1)
}
}
})
也是现场测试:https://jsfiddle.net/m10jyLut/7/
不知道我的设计是否正确。我想避免过于陈腐的解决方案。
非常感谢您的猜测。
我在 v-for 中添加了“key”,这总是一个好主意,并通过 toggle() 传递 todo.id。
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="todo in todos" :key="todo.id">
<label>
<input type="checkbox"
v-on:change="toggle(todo.id)">
{{ todo.text }}
</label>
</li>
</ol>
</div>
你的脚本标签应该是这样的:
new Vue({
el: "#app",
data: {
todos: [
{ id: Math.random() * 100000, text: "Learn JavaScript", },
{ id: Math.random() * 100000, text: "Learn Vue", },
{ id: Math.random() * 100000, text: "Play around in JSFiddle", },
{ id: Math.random() * 100000, text: "Build something awesome", }
]
},
methods: {
toggle(id) {
this.todos = this.todos.filter(todo => todo.id !== id)
}
}
})
在 Vue.js 中,将 key 添加到 v-for 并使用 ids 进行渲染操作总是一个好主意。