programing

v-for에 의해 렌더링된 개체 내에서 변경 사항이 발생할 때 DOM을 업데이트하는 방법

prostudy 2022. 5. 2. 20:29
반응형

v-for에 의해 렌더링된 개체 내에서 변경 사항이 발생할 때 DOM을 업데이트하는 방법

나는 사용하고 있다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을 업데이트할 수 있는 방법이 있는가?this.$forceUpdate()에서changeCategory(index)기능?

편집: 변경됨mapforEach, DOM은 여전히 업데이트되지 않는다.

편집: 형식 설명과 함께 vue-class 구성 요소를 사용하는 경우

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

그 문제에 대해 논의한 후 나는 다음과 같은 대체 방법을 제안했다.

추가하다activeIndexdata템플릿을 다음으로 변경하십시오.

<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재산은 에 추가되었다.categoryVue의 변화 감지 주의사항 중 하나에 속함.

이것은 예상대로 효과가 있다.당신의 문제는 당신이 여기에 게시한 코드에 있지 않다. (지도 사용에도 불구하고 지도 내에서 객체는 참조이므로, 그들의 멤버를 수정하면 원래의 객체가 수정된다.)

new Vue({
  el: '#app',
  data: {
    categories: [{
        service_type_name: 'one',
        active: false
      },
      {
        service_type_name: 'two',
        active: false
      }
    ]
  },
  methods: {
    changeCategory(index) {
      this.categories.map((c, i) => {
        c.active = (i != index) ? false : true
      })
    }
  }
});
.active {
  background-color: lightgray;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js"></script>
<ul id="app">
  <li v-for="category, i in categories" :class="{active: category.active}" @click="changeCategory(i)">
    <a>{{ category.service_type_name }}</a>
  </li>
</ul>

참조URL: https://stackoverflow.com/questions/43721768/how-to-update-dom-when-changes-occurs-within-an-object-rendered-by-v-for

반응형