Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Vuex map helpers with Composition API

I am using Composition API in Vue2. Can you tell me how to access mapState with composition API? I want to watch for state changes as well. Hence I would have to use it within setup function as well (not only in return). Thanks

like image 703
Purni Avatar asked Sep 11 '25 16:09

Purni


2 Answers

The Vuex map helpers aren't supported (yet?) in the Vue 2 or Vue 3 composition API, and this proposal for them has been stalled for a while.

You'll have to manually create a computed like in the docs:

const item = computed(() => store.state.item);

A more complete example:

import { computed } from 'vue';
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore();
    const item = computed(() => store.state.item);

    return {
      item
    };
  }
}
like image 152
Dan Avatar answered Sep 14 '25 11:09

Dan


For me the trick was using the vuex-composition-helper npm package.

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
        }
    }
}
like image 39
dpointeck Avatar answered Sep 14 '25 10:09

dpointeck