【问题标题】:How to access Vuex map helpers with Composition API如何使用 Composition API 访问 Vuex 地图助手
【发布时间】:2021-05-29 11:30:38
【问题描述】:

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

【问题讨论】:

    标签: vue.js vuejs2 vuex vuejs3 vue-composition-api


    【解决方案1】:

    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 4 是否支持 Vuex 映射器助手?
    • 按照提案后好像没有。哦,好吧...
    【解决方案2】:

    对我来说,诀窍是使用 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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2022-11-28
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      相关资源
      最近更新 更多