programing

Vue JS: 데이터 반환 내부의 값을 업데이트하는 방법

copyandpastes 2022. 7. 13. 21:41
반응형

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

반응형