vue.js - 当 v-for 渲染的对象发生变化时如何更新 DOM?

标签 vue.js vuejs2 vue-component v-for

我正在使用 v-for 来呈现基于对象数组的列表。

<ul>
  <li v-for="category, i in categories"
  :class="{active: category.active}"
  @click="changeCategory(i)">
    <a>{{ category.service_type_name }}</a>
  </li>
</ul>

当您单击列表项时 changeCategory(index) 运行:

changeCategory(index) {
    this.categories.forEach((c, i) => {
        c.active = (i != index)? false : true
    })
}

所以点击的列表项 active 属性被设置为 true 并且所有其他设置为 false ,列表项得到一个添加了 .active 类(因为模板中的 :class="{active: category.active}" 行。

但是,DOM 不会更新以显示此更改。

是否可以在发生此更改时自动更新 DOM,而无需在 changeCategory(index) 函数中使用 this.$forceUpdate()

编辑:将map更改为forEach,DOM仍然没有更新。

编辑:我正在使用 vue-class-components 和 typescript

import Vue from 'app/vueExt'
import { Component } from 'vue-property-decorator'
import * as Template from './services.vue'

@Component({
    mixins: [Template]
})
export default class Services extends Vue {
    categories = []

    created() {
        this.api.getServiceSetupCatagories().then((res) => {
            this.categories = res.categories
            this.categories.forEach((c, i) => {
                // adding active property to the object
                // active = true if i = 0, false otherwise
                c.active = (i)? false : true
            })
        })
    }

    changeCategory(index) {
        this.categories.forEach((c, i) => {
            c.active = (i != index)? false : true
        })
    }
}

最佳答案

在讨论了这个问题之后,我提出了以下替代方法。

activeIndex 添加到data 并将模板更改为以下内容。

<ul>
  <li v-for="category, i in categories"
      :class="{active: activeIndex === i}"
      @click="activeIndex = i">
    <a>{{ category.service_type_name }}</a>
  </li>
</ul>

这似乎适用于@wrahim。

我相信原始代码的潜在问题是 active 属性被添加到 category 中,属于 Vue 的 change detection caveats 之一。 .

关于vue.js - 当 v-for 渲染的对象发生变化时如何更新 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43721768/

相关文章:

javascript - 如何在 VUE 2.0 组件之间创建事件 Hook

javascript - vue中如何获取被点击的项目

javascript - vue-async-data 不工作

javascript - 有没有办法根据用户角色为一条路线加载不同的 View ?

javascript - 带有 bootstrap-vue 的静态 html 和 vue

css - 在vue中给backgroundImage添加过渡效果

javascript - 属性或方法 "sendResetMail"未在实例上定义,但在渲染期间引用

javascript - Vuex 存储我所有的产品信息和API请求查询

javascript - Vue.js 将数据从插槽传递到组件实例

php - laravel 5.4 Vue 组件不工作