반응형
Vue JS: 데이터 반환 내부의 값을 업데이트하는 방법
웹 사이트에 css 코드를 표시하기 위해 vue-codemirror 패키지를 사용하고 있습니다.문제는 vuex에서 상태를 업데이트하는 방법을 이해하지 못한다는 것입니다.
<div>
<codemirror v-model="code" />
<button @click="change">click</button>
{{ $store.state.background }}
</div>
methods: {
change() {
Vue.set(this.$store.state, "background", "#242424");
},
},
data() {
return {
code: dedent`
/* Some example CSS */
body {
margin: ${this.$store.state.background};
padding: 3em 6em;
}
`,
};
},
Vuex
export default new Vuex.Store({
state: {
background: "#000",
},
});
문제는 반응성이라고 생각하고Vue.set
를 클릭하면click
버튼, 값{{ $store.state.background }}
변경은 되지만 내부 코드는 변경되지 않습니다.data
return
변하지 않다
이 예는 codesandbox에서도 확인할 수 있습니다.
@vanblart 코멘트처럼 데이터 대신 계산된 속성을 생성할 수 있습니다.
computed: {
code() { return dedent(`
/* Some example CSS */
body {
margin: ${this.$store.state.background};
padding: 3em 6em;
}
`)
}
Vuex에서는 값을 설정하기 위한 액션/변환을 생성할 수 있습니다.
mutations: {
addBkg(state, val) {
state.background = val
},
},
actions: {
setBkg({ commit }, data) {
commit("addBkg", data);
},
},
그리고 메토스에서 그 액션을 디스패치한다:
change() {
this.$store.dispatch("setBkg", "#242424");
},
언급URL : https://stackoverflow.com/questions/70900054/vue-js-how-to-update-the-value-that-is-inside-data-return
반응형
'programing' 카테고리의 다른 글
Java Streams가 일회성인 이유는 무엇입니까? (0) | 2022.07.13 |
---|---|
v-on 핸들러 오류: "ReferenceError: i18n이 정의되지 않았습니다." (0) | 2022.07.13 |
Python: * 및 **가 / 및 sqrt()보다 빠른 이유는 무엇입니까? (0) | 2022.07.13 |
JAX-RS 및 Jersey를 사용한 REST 토큰 기반 인증 구현 방법 (0) | 2022.07.13 |
C 함수는 왜 네임 매니지먼트가 안 되나요? (0) | 2022.07.13 |