简体   繁体   English

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

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

Well, it's not easy to explain.好吧,这并不容易解释。

I have a list of checkboxes generated from reactive data .我有一个从反应数据生成的复选框列表 When you check one of the checkboxes, one of the entries of the reactive data is deleted.当您选中其中一个复选框时,将删除反应数据的条目之一。

The list is then updated .然后更新列表

The next checkbox is then placed under the mouse cursor and is "activated" by releasing the mouse button .然后将下一个复选框放置在鼠标 cursor 下方,并通过释放鼠标按钮“激活” This behavior is unwanted, can you see a way to avoid this?这种行为是不受欢迎的,您能找到避免这种情况的方法吗?

Here is the code to illustrate this case:这是说明这种情况的代码:

<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>

Script part:脚本部分:

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)
    }
  }
})

Also a live test: https://jsfiddle.net/m10jyLut/7/也是现场测试: https://jsfiddle.net/m10jyLut/7/

I don't know if my design is correct.我不知道我的设计是否正确。 I would like to avoid a too hackneyed solution.我想避免过于陈腐的解决方案。

Thank you very much for your guess.非常感谢您的猜测。

I added "key" to v-for, which is always a good idea, and passing todo.id with toggle().我在 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>

Your script tag should be like this:你的脚本标签应该是这样的:

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)
    }
  }
})

In Vue.js, it's always a good idea to add key to v-for, and working with ids for rendering operations.在 Vue.js 中,将 key 添加到 v-for 中并使用 ids 进行渲染操作总是一个好主意。

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

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