반응형
데이터 변수가 Vue.js의 계산된 속성에 대해 Vuex에서 업데이트되지 않음
바이올린: https://jsfiddle.net/mjvu6bn7/
비동기적으로 설정되는 Vuex 스토어 변수에 종속된 계산된 속성에 워처가 있습니다.Vue 컴포넌트의 데이터 변수를 설정하려고 하는데, 이 계산 속성이 변경되고 있을 때 설정되지 않습니다.
Vue 컴포넌트는 다음과 같습니다.
new Vue({
el: '#app',
store,
data : {
myVar : ""
},
beforeMount() {
this.$store.dispatch('FETCH_PETS', {
}).then(() => {
console.log("fetched pets")
})
},
computed:{
pets(){
return this.$store.state.pets
}
},
watch:{
pets: (pets) => {
console.log("Inside watcher")
this.myVar = "Hey"
}
}
});
Vuex 스토어는 다음과 같습니다.
const state = {
pets: []
};
const mutations = {
SET_PETS (state, response) {
console.log("SET_PETS")
state.pets = response;
}
};
const actions = {
FETCH_PETS: (state) => {
setTimeout(function() {
state.commit('SET_PETS', ['t7m12qbvb/apple_9', '6pat9znxz/1448127928_kiwi'])
}, 1000)
}
}
const store = new Vuex.Store({
state,
mutations,
actions
});
여기에 이것을 위해 만들어진 바이올린입니다.보시다시피 myVar는 업데이트되지 않지만 애완동물이 로드되면 워처가 호출됩니다.
ES6 화살표 함수가 키워드를 구속하지 않는다는 사실을 놓쳤습니다(화살표 함수는 단순히 일반적인 통사적 설탕이 아닙니다).function
)의 예에서는,this
내부pets
워처는 디폴트로window
그리고.myVar
Vue 인스턴스는 설정되지 않습니다.다음과 같이 코드를 변경하면 정상적으로 동작합니다.
watch: {
pets(pets) {
console.log("Inside watcher")
this.myVar = "Hey"
}
}
왜냐하면 내적 기능에서 기대하는 것이 아니기 때문입니다.
이것을 시험해 보세요.
watch:{
var that = this;
pets: (pets) => {
console.log("Inside watcher")
that.myVar = "Hey"
}
언급URL : https://stackoverflow.com/questions/40546323/data-variable-not-being-updated-from-watcher-on-computed-property-in-vue-js-with
반응형
'IT이야기' 카테고리의 다른 글
Vue.js에서 .appendChild와 함께 추가된 동적 요소에 v-model 연결 (0) | 2022.06.28 |
---|---|
C/C++: 헤더 파일의 정적 함수, 무슨 의미입니까? (0) | 2022.06.28 |
bootstrap-vue에서 b-form-checkbox-group에 필요한 검증을 설정하는 방법 (0) | 2022.06.28 |
Vue/Vuex 서브스크라이버가 기동하지 않는 이유는 무엇입니까? (0) | 2022.06.28 |
Vuex에서 값을 반환하는 VueJ가 작동하지 않음 (0) | 2022.06.28 |