어레이의 개체를 변경하고 반응성을 트리거합니다.
배열에서 인덱스로 발견된 개체의 일부를 변경할 때 업데이트를 트리거하려면 어떻게 해야 합니까?
문서에서는 배열 값을 변경하는 방법을 보여 줍니다.
Vue.set(example1.items, indexOfItem, newValue)
또는
example1.items.splice(indexOfItem, 1, newValue)
그러나 개체의 나머지 부분을 변경하지 않고 배열에 있는 개체의 속성 값을 변경하려면 어떻게 해야 합니까?
다음은 속성을 업데이트하기 위해 작동하지만 Vue는 다른 항목이 업데이트를 트리거할 때까지 변경에 응답하지 않습니다.
example1.items[indexOfItem].some_object_property = false
어레이 요소의 하위 속성을 로 업데이트할 수 있습니다. 예를 들어,x
처음 2개의 어레이 요소의 서브프로퍼티(존재하지 않는 경우 서브프로퍼티 작성):
methods: {
update() {
this.$set(this.arr[0].foo, 'x', (this.arr[0].foo.x || 0) + 100)
this.$set(this.arr[1].foo, 'x', (this.arr[1].foo.x || 0) + 100)
}
}
new Vue({
el: '#app',
data() {
return {
arr: [
{
foo: {
x: 100,
y: 200
}
},
{
foo: {
/* x does not exist here initially */
y: 400
}
}
]
};
},
methods: {
update() {
this.$set(this.arr[0].foo, 'x', (this.arr[0].foo.x || 0) + 100)
this.$set(this.arr[1].foo, 'x', (this.arr[1].foo.x || 0) + 100)
}
}
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
<div id="app">
<button @click="update">Update</button>
<p>arr[0]: {{ arr[0] }}</p>
<p>arr[1]: {{ arr[1] }}</p>
</div>
set()를 한 번 호출하여 어레이 내의 오브젝트(업데이트할 속성 포함)를 설정하는 한 Vue는 오브젝트 속성 변경에 응답합니다.다음은 앱의 데이터에서 초기화된 개체 배열과 마운트 시 Vue.set()을 사용하여 수동으로 설정된 개체 배열의 예입니다).버튼을 클릭하면 해당 어레이의 각 개체에 대한 속성이 업데이트되고 Vue가 대응합니다.mount()에서 발생하는 set() 콜은 실제로 언제든지 발생할 수 있습니다.
https://codepen.io/jordan-kalosal/pen/VrwjoR
new Vue({
el: "#app",
data: {
arr: [
{
property: 'OBJ1 Prop'
},
{
property: 'OBJ2 Prop'
}
],
setLater: false
},
mounted() {
this.$set(this, 'setLater', [
{
property: 'setLater OBJ1 Prop'
},
{
property: 'setLater OBJ2 Prop'
}
])
},
methods: {
_updateObjProps() {
this.arr[0].property = (new Date()).toString();
this.setLater[0].property = (new Date()).toString();
}
}
})
다음은 어레이 내의 객체의 반응성을 잘 보여주는 또 다른 데모 예입니다.라이브로 체험해 보세요.https://codepen.io/antoniandre/pen/ZdjwKG
JS
new Vue({
el: "#app",
data: {
array: []
},
methods: {
addTimeProp() {
this.array.forEach(item => {
this.$set(item, 'time', null)
})
},
updateTimeProp() {
this.array.forEach(item => {
item.time = (new Date()).toString()
})
}
},
created () {
this.array.push({ name: 'today' }, { name: 'tomorrow' })
}
})
HTML: PUG
#app
h1 Reactivity of objects inside an array
h2 Content of the array
pre {{ array }}
button(@click="array.push({ name: 'another day' })") Add another object
button(@click="addTimeProp") Add `time` property
button(@click="updateTimeProp") Update `time` property
새 속성을 생성하지 않은 경우에도 다음과 같이 수행할 수 있습니다.
this.myArray.find( el => el.id === '123').someValue = 'someValue'
어레이 내의 오브젝트는 완전히 반응합니다.
언급URL : https://stackoverflow.com/questions/46985067/vue-change-object-in-array-and-trigger-reactivity
'itsource' 카테고리의 다른 글
사전 로드된 상태의 사용자 지정 nuxt 500 오류 페이지 (0) | 2022.07.21 |
---|---|
VueJ는 데이터를 개체로 가져옵니다. (0) | 2022.07.21 |
Quasar로 마이크로 프런트엔드를 구축하는 방법 (0) | 2022.07.21 |
vue.js의 하위 구성 요소에 데이터를 전달하는 방법 (0) | 2022.07.21 |
vuex 작업 반환의 메서드가 정의되지 않았습니다. (0) | 2022.07.21 |