programing

VueJ가 어레이의 개체에 이 속성이 추가되었음을 감지하는 이유는 무엇입니까?

prostudy 2022. 7. 29. 22:16
반응형

VueJ가 어레이의 개체에 이 속성이 추가되었음을 감지하는 이유는 무엇입니까?

에는 2개의 컴포넌트가 각 컴포넌트에는 Vue 컴포넌트가 .items2번입니다.컴포넌트의 은 각음음음음음음음음음음음음 of of of of of of of of의 오브젝트를 설정되어 .items어레이(해당 오브젝트일 경우)show트루티의 첫 에 ""가 .show의 의 값true show값을 설정합니다.

new Vue({
  el: '#ex1',
  data: () => ({ items: [{name: 'apple', show: true}, {name: 'banana'}] }),
  mounted() {
    // 2nd item's show property setting is not detected here
    this.items[1].show = true; 
  }
})

new Vue({
  el: '#ex2',
  data: () => ({ items: [{name: 'apple', show: true}, {name: 'banana'}] }),
  mounted() {
    // 2nd item's show property setting IS detected...
    this.items[1].show = true; 
    
    // ...when the 1st item's show property is set to false
    this.items[0].show = false; 
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="ex1">
  Example 1:
  <div v-if="items[0].show">{{ items[0] }}</div>
  <div v-if="items[1].show">{{ items[1] }}</div>
</div>

<div id="ex2">
  Example 2:
  <div v-if="items[0].show">{{ items[0] }}</div>
  <div v-if="items[1].show">{{ items[1] }}</div>
</div>

번째 예에서는 ""를 했습니다.show의 두 속성itemstrue Vue는 템플릿의 변경을 검출하지 않습니다(예상대로).

에서는 '어울리다', '어울리다'를 했습니다.show .true 을 설정해 주세요.show '''입니다.false이 경우 Vue는 두 요소의 변경을 검출합니다.items를 배열하고 그에 따라 템플릿을 업데이트합니다.Vue의 '변경 감지 경고'를 고려하면 이러한 상황은 예상할 수 없습니다.

이것은 꽤 무해한 버그인 것 같기 때문에 보고할 가치가 있는지 잘 모르겠습니다.하지만 이 행동을 설명할 수 있는 사람이 있을까 해서요.가 Vue의 하는 이유는 입니까?show두 번째 예에서 객체에 속성을 적용합니까?

반응 특성 변경(show첫 번째 오브젝트의 경우)를 트리거합니다.Vue는 템플릿에서 참조하는 개체의 현재 상태를 충실하게 렌더링합니다. 여기에는 두 번째 개체가 포함됩니다.

두 번째 개체의 show 속성은 여전히 반응하지 않으며 Vue를 변경해도 업데이트되지 않습니다.단순히 업데이트를 트리거하는 첫 번째 개체의 반응 속성 상태가 변경됩니다.

즉, 두 번째 객체의 show 속성을 변경해도 Vue는 갱신되지 않지만 첫 번째 객체의 show 속성을 변경하면 항상 갱신되며 추가된 방법에 관계없이 업데이트는 어레이의 현재 상태를 렌더링합니다.

난 이걸 버그라고 생각하지 않아.

그 차이를 쉽게 알 수 있는 한 가지 방법은 업데이트 후 어레이를 콘솔에 기록하는 것입니다.두 번째 오브젝트의 show property는 관찰되지 않지만 존재하는 것을 알 수 있습니다.

편집 코멘트를 바탕으로 조금 더 명확하게 하고 싶었습니다.두 번째 개체에 대한 변경 내용이 Vue에 나타나는 이유는 전체 Vue가 다시 렌더링되고 두 번째 개체가 Vue에서 직접 참조되기 때문입니다.예를 들어 컴포넌트에 값을 전달하면 두 번째 오브젝트는 다시 렌더링되지 않습니다.

다음 예시는 컴포넌트가 렌더링을 관리하므로 값이 컴포넌트에 전달될 때 두 번째 오브젝트가 업데이트되지 않음을 보여줍니다.

console.clear()
 
 Vue.component("item", {
  props: ["item"],
  template: `
    <div>Item Show: {{item.show}}</div>
  `
 })
 
 new Vue({
      el: '#ex2',
      data: () => ({ items: [{name: 'apple', show: true}, {name: 'banana'}] }),
      mounted() {
        // 2nd item's show property setting IS detected...
        this.items[1].show = true; 
        
        // ...when the 1st item's show property is set to false
        this.items[0].show = false; 
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="ex2">
  This will show false, because that is the current state and this object's show
  property is reactive
  <item :item="items[0]"></item>
  <hr>
  This will not show *anything*, despite the current state of show=true
  because the object's show property is not reactive
  <item :item="items[1]"></item>
</div>

다음 링크에 기재되어 있습니다.

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object using the Vue.set(개체, 키, 값)

해결하도록 하겠습니다.show = true는 다음과 같이 쓸 수 있습니다.

Vue.set(this.items[1], 'show', true)

맑기를 바라다

언급URL : https://stackoverflow.com/questions/48811472/why-is-vuejs-detecting-this-property-being-added-to-an-object-in-an-array

반응형