如果我这样设计我的组件:
<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 }}
为什么在这种情况下不反应?