1

当我在重复的 div 中有一个单击处理程序时v-for,似乎在该单击处理程序中所做的更改不会在 DOM 中更新。

为什么?

https://jsfiddle.net/AndersBillLinden/109uzsx7/27/

html:

<div id="vue">
  <input type="checkbox" v-model="force_update"/> force update
  <div v-for="e in arr">
    {{e.id}} = {{e.text}}
    <a href="#" @click="on_link_clicked(e)">click</a>
    <span v-show="e.clicked"> clicked</span>
  </div>
</div>

js:

new window.Vue(
{
  el: '#vue',
  data:
  {
    arr: [{id:1,text:"one"}, {id:2, text:"two"}, {id:3, text:"three"}],
    force_update: true
  },
  methods:
  {
    on_link_clicked(e)
    {
      e.clicked = true;
      
      if (this.force_update)
        this.$forceUpdate();
    }
  }
});

在此处输入图像描述

点击链接1

在此处输入图像描述

取消选中强制更新

在此处输入图像描述

点击第二个链接

在此处输入图像描述

(什么都没发生)

检查“强制更新”

在此处输入图像描述

现在呈现上一步中的更改。

结论是我们有时需要强制更新,但不清楚原因。

4

1 回答 1

2

更改e.clicked = true;为,this.$set(e, 'clicked', true)以便为模型中尚不存在的属性添加反应性。

于 2021-06-09T12:43:15.663 回答