programing

Vuex 및 Composition API를 사용하여 사후 대응 속성에 액세스할 수 있는 방법이 있습니까?

goodcopy 2022. 8. 2. 23:40
반응형

Vuex 및 Composition API를 사용하여 사후 대응 속성에 액세스할 수 있는 방법이 있습니까?

내 컴포넌트를 다음과 같이 설계할 경우:

<template>
  <div>
    <button @click="increment">Count is: {{ store.getters.count }}</button>
  </div>
</template>

<script>
import { reactive } from "@vue/composition-api";
import store from "../store";

export default {
  name: "Count",

  setup() {
    const state = reactive({
      store
    });
    const increment = () => {
      store.dispatch.increment();
    };
    return {
      ...state,
      increment
    };
  }
};
</script>

그리고 제 스토어는 다음과 같이 정의됩니다.

import Vue from "vue";
import Vuex from "vuex";
import { createDirectStore } from "direct-vuex";

Vue.use(Vuex);

const {
  store,
  rootActionContext,
  moduleActionContext,
  rootGetterContext,
  moduleGetterContext
} = createDirectStore({
  state: {
    count: 0
  },
  getters: {
    count: state => state.count
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    increment(context) {
      context.commit("increment");
    }
  }
});

// Export the direct-store instead of the classic Vuex store.
export default store;

// The following exports will be used to enable types in the
// implementation of actions and getters.
export {
  rootActionContext,
  moduleActionContext,
  rootGetterContext,
  moduleGetterContext
};

// The following lines enable types in the injected store '$store'.
export type AppStore = typeof store;
declare module "vuex" {
  interface Store<S> {
    direct: AppStore;
  }
}

카운트에 더 잘 접근할 수 있는 방법은 없을까?{{ store.getters.count }}템플릿에 저장하시겠습니까?이상적으로는 다음과 같이 접근하고 싶습니다.{{ count }}, 그러나 그것은 단지store반응합니다.즉, 증분 액션을 디스패치하면 카운트를 다양한 방법으로 정의하려고 해도 "{ count }}"이 갱신되지 않습니다.제가 시도한 것은 다음과 같습니다.

  setup() {
    const state = reactive({
      store,
      count: store.getters.count
    });
    const increment = () => {
      store.dispatch.increment();
    };
    return {
      ...state,
      count: state.count,
      increment
    };
  }

왜?{{ count }}반응할 수 있을까요?

count: store.getters.count현재 값을 저장하고 있는 것을 의미합니다.store.getters.count디폴트값으로서count.

반응하지 않을 거란 뜻이죠주의해 주세요count스토어 내에는 함수가 있습니다.

네 입장을 밝혀볼 수도 있어count적절하게 갱신할 수 있도록 계산된 속성을 대신 사용합니다.

Composition API는 아직 시도하지 않았지만 도움이 되었으면 합니다.

언급URL : https://stackoverflow.com/questions/60498766/using-vuex-and-the-composition-api-is-there-a-way-to-access-reactive-properties

반응형