programing

Vuex 스토어 상태가 변형될 때 Vue App 상태가 업데이트되지 않음

subpage 2023. 6. 28. 21:43
반응형

Vuex 스토어 상태가 변형될 때 Vue App 상태가 업데이트되지 않음

저는 몇 달 동안 Vue를 사용했지만, 지금은 Vuex를 앱에 통합하려고 하지만 Vuex 저장소가 변형될 때 상태를 업데이트할 수 없습니다.

새 앱을 만들고 작동하는지 확인하기 위해 간단한 카운트를 구현했지만 여전히 업데이트되지 않습니다.count언제store.count변경되었습니다.제 테스트 코드는 아래와 같습니다.

index.html:

<div id="app">
    <template>
        <h1>{{count}}</h1>
        <button @click="add">Add 1</button>
    </template>
</div>

index.js:

import Vue from 'vue/dist/vue.js';

import store from './store';

new Vue({
    el: '#app',
    store,
    data: {},
    computed: {
        count: () => store.state.count
    },
    methods: {
        add: () => store.commit('add')
    }
});

store.js:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        add: (state) => state.count++
    }
});

알고있어요store.countVue dev 도구에서 볼 수 있기 때문에 업데이트되고 있습니다.나는 왜 그것이count값도 업데이트되지 않습니다. 무엇이 누락되었습니까?

문제는 당신의 수입품일 가능성이 큽니다.Vue이내에index.js다음에서 변경해 보십시오.

import Vue from 'vue/dist/vue.js';

받는 사람:

import Vue from 'vue';

이렇게 하면 Vuex가 올바르게 등록될 수 있습니다.

다음을 사용하여 프로젝트를 만들었습니다.@vue/cliVuex를 사용합니다.주/인덱스 가져오기 위치vue/dist/vue.js의 대신에vue액세스할 수 있는 것을 포함하여 Vuex를 효과적으로 등록하지 못했습니다.this.$store하위 구성 요소에 있습니다.

그것이 도움이 되기를 바랍니다!

조치에 대한 설명서에 명시된 대로

작업에는 임의의 비동기 작업이 포함될 수 있습니다.

당신의 경우, 다음을 클릭하세요.add-button은 비동기 코드를 실행합니다.반면에 돌연변이는 동기적이며 응용 프로그램 전체에서 값을 지속적으로 유지합니다.돌연변이는 다음을 통해 만들어질 수 있습니다.commit문(예:store.commit("add").

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  // Synchronous methods for modifying the values in the state.
  // They are handed a `state` from the store.
  mutations: {
    add: state => state.count++
  },
  // Asynchronous methods that can call mutation methods to mutate the state via commits.
  // They are handed a context of the `store`.
  actions: {
    add: store => store.commit("add")
  }
});

CodeSandbox에서 전체 작업 예제를 참조하십시오.

언급URL : https://stackoverflow.com/questions/56190522/vue-app-state-not-updating-when-vuex-store-state-mutates

반응형