如何使用 Composition API 访问 Vuex 地图助手

How to access Vuex map helpers with Composition API

我在 Vue2 中使用组合 API。你能告诉我如何使用组合 API 访问 mapState 吗?我也想观察状态变化。因此,我也必须在设置函数中使用它(不仅在 return 中)。谢谢

Vuex 地图助手在 Vue 2 或 Vue 3 组合中不受支持(目前?)API,并且 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
        }
    }
}