【问题标题】:Vuejs strange behavior when a list of checkboxes are updated更新复选框列表时的Vuejs奇怪行为
【发布时间】:2020-10-08 22:23:33
【问题描述】:

嗯,不好解释。

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

列表随即更新

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

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

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

我不知道我的设计是否正确。我想避免一个过于陈旧的解决方案。

非常感谢您的猜测。

【问题讨论】:

    标签: javascript vue.js checkbox vue-reactivity


    【解决方案1】:

    我在 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 中,向 v-for 添加 key 并使用 id 进行渲染操作总是一个好主意。

    【讨论】:

    • 当我使用索引作为动态列表的键时,我遇到了一些错误和不需要的行为。自从我一直在创建 ids 并用于 key。据我了解,键必须是不可改变的,但是当我添加或删除项目时,索引会发生变化。
    • 有效地,不可变标识符解决了我的问题,非常感谢。
    • 我尝试过使用 Array 的“自然”索引,但这不能解决问题:jsfiddle.net/m10jyLut/12。最好的解决方案实际上是在引用时添加一个不可变索引。
    猜你喜欢
    • 1970-01-01
    • 2015-10-04
    • 2021-11-25
    • 2020-01-30
    • 2015-04-01
    • 2020-08-29
    • 2016-11-27
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多