繁体   English   中英

更新复选框列表时 Vuejs 的奇怪行为

[英]Vuejs strange behavior when a list of checkboxes are updated

好吧,这并不容易解释。

我有一个从反应数据生成的复选框列表 当您选中其中一个复选框时,将删除反应数据的条目之一。

然后更新列表

然后将下一个复选框放置在鼠标 cursor 下方,并通过释放鼠标按钮“激活” 这种行为是不受欢迎的,您能找到避免这种情况的方法吗?

这是说明这种情况的代码:

<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 进行渲染操作总是一个好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM