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