vue.displaces 구성 api 및 sfc를 사용하여 vuex의 어레이 상태 변경 감시
vuex 상태 변화를 관찰하려고 합니다.상태는 어레이입니다.버튼을 눌러서 그 배열의 값을 변경합니다.이 버튼을 누르면 배열(vuex 상태)이 바뀔 때마다 화면에 값을 목록으로 표시하고 싶습니다.
이것은 메인 vuex 스토어입니다.
import { createStore } from 'vuex';
import rollingModule from './modules/rolling/index.js';
const store = createStore({
modules: {
rolling: rollingModule,
},
});
export default store;
vuex 스토어 모듈입니다.
export default {
namespaced: true,
state() {
return {
numbers: [0, 0, 0, 0, 0],
};
},
mutations: {
rollDice(state, payload) {
state.numbers = payload;
},
},
actions: {
rollDice(context) {
const rolledNumbers = [];
for (let i = 0; i < 5; i++) {
rolledNumbers.push(Math.floor(Math.random() * 7));
}
context.commit('rollDice', rolledNumbers);
},
},
getters: {
getNumbers: (state) => state.numbers,
},
};
나의 첫 번째 시도는 변화에 반응하기 위해 계산된 속성을 사용하는 것이었지만 그것은 효과가 없는 것 같다.그런 다음 계산 속성의 워처를 console.log에 추가했지만 워처는 해고되지 않는 것 같습니다.
내 컴포넌트 코드는 다음과 같습니다.
<template>
<ul>
<li v-for="number in rolledNumbers" :key="number">
{{ number }}
</li>
</ul>
</template>
<script setup>
import { computed, watch } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const rolledNumbers = computed(() => {
store.getters['rolling/getNumbers'];
});
watch(rolledNumbers, (newValue, oldValue) => {
console.log('Old Array: ' + oldValue);
console.log('New Array: ' + newValue);
});
</script>
배열 값의 변화를 관찰하기 위해 딥워치에 관한 기사를 읽었는데 composition api 및 composition api에 적합한 것을 찾을 수 없었습니다.
편집 1: 중첩된 요소가 변경되면 감시자가 실행됩니다.그 코드는 다음과 같습니다.
watch(
rolledNumbers,
(newValue, oldValue) => {
console.log('Old Array: ' + oldValue);
console.log('New Array: ' + newValue);
},
{ deep: true }
);
안타깝게도 oldValue와 newValue가 모두 정의되지 않았습니다.
변환에 의해 어레이가 치환되고 있습니다.numbers
완전히 새로운 어레이를 탑재했습니다.즉, 어레이에 대한 참조가 손실되어 반응성이 저하됩니다.
rollDice(state, payload) {
state.numbers = payload;
}
참조를 유지하려면 배열의 내용을 교체해야 합니다.다음과 같은 작업을 수행할 수 있습니다.
rollDice(state, payload) {
# Remove all items from the array
state.numbers.length = 0
# Fill the array with the items from the payload array
[].push.apply(state.numbers, payload)
}
언급URL : https://stackoverflow.com/questions/70480198/vue-js-watching-array-state-change-in-vuex-using-composition-api-and-sfc
'programing' 카테고리의 다른 글
JS 파일에서 Nuxt 프로젝트의 Vuex 스토어 액세스 (0) | 2022.08.08 |
---|---|
지정된 문자 수로 문자열 생성 (0) | 2022.08.08 |
고유한 vuex 저장소 인스턴스를 사용해야 하는 구성 요소를 재사용하는 방법 (0) | 2022.08.07 |
Nuxt/Vue.js - 프로포트를 기반으로 자 컴포넌트에 동적으로 로드 (0) | 2022.08.07 |
Vue.js에서 가져온 소스에서 개체의 실제 값 가져오기 (0) | 2022.08.07 |