2

如果我这样设计我的组件:

<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 }}为什么在这种情况下不反应?

4

1 回答 1

1

count: store.getters.count表示您将 的当前值存储store.getters.count为 state 的默认值count

这意味着它不会是被动的。请注意,count在 store 中是一个函数。

您可以尝试将您的状态count设置为计算属性,以便正确更新。

我还没有尝试过 Composition API,但我希望能帮上忙。

于 2020-03-03T02:11:41.187 回答