【发布时间】:2021-05-29 11:30:38
【问题描述】:
我在 Vue2 中使用 Composition API。你能告诉我如何使用组合 API 访问 mapState 吗?我也想观察状态变化。因此,我也必须在 setup 函数中使用它(不仅仅是作为回报)。谢谢
【问题讨论】:
标签: vue.js vuejs2 vuex vuejs3 vue-composition-api
我在 Vue2 中使用 Composition API。你能告诉我如何使用组合 API 访问 mapState 吗?我也想观察状态变化。因此,我也必须在 setup 函数中使用它(不仅仅是作为回报)。谢谢
【问题讨论】:
标签: vue.js vuejs2 vuex vuejs3 vue-composition-api
Vue 2 或 Vue 3 组合 API 不支持 Vuex 地图助手(还没有?),他们的 proposal 已经停止了一段时间。
您必须在docs 中手动创建一个类似的计算:
const item = computed(() => store.state.item);
一个更完整的例子:
import { computed } from 'vue';
import { useStore } from 'vuex';
export default {
setup() {
const store = useStore();
const item = computed(() => store.state.item);
return {
item
};
}
}
【讨论】:
对我来说,诀窍是使用 vuex-composition-helper npm 包。
https://www.npmjs.com/package/vuex-composition-helpers
import { useState, useActions } from 'vuex-composition-helpers';
export default {
props: {
articleId: String
},
setup(props) {
const { fetch } = useActions(['fetch']);
const { article, comments } = useState(['article', 'comments']);
fetch(props.articleId); // dispatch the "fetch" action
return {
// both are computed compositions for to the store
article,
comments
}
}
}
【讨论】: