A util package to use Vuex with Composition API easily.

Overview

vuex-composition-helpers

CI npm version

A util package to use Vuex with Composition API easily.

Installation

$ npm install vuex-composition-helpers

This library is not transpiled by default. Your project should transpile it, which makes the final build smaller and more tree-shakeable. Take a look at transpiling.

Non-typescript projects may import the library from the dist subdirectory, where plain javascript distribution files are located.

import { useState, ... } from 'vuex-composition-helpers/dist';

Basic Usage Examples

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
		}
	}
}

Namespaced Usage Examples

import { createNamespacedHelpers } from 'vuex-composition-helpers';
const { useState, useActions } = createNamespacedHelpers('articles'); // specific module name

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
		}
	}
}

You can also import your store from outside the component, and create the helpers outside of the setup method, for example:

import { createNamespacedHelpers } from 'vuex-composition-helpers';
import store from '../store'; // local store file
const { useState, useActions } = createNamespacedHelpers(store, 'articles'); // specific module name
const { fetch } = useActions(['fetch']);

export default {
	props: {
		articleId: String
	},
	setup(props) {
		const { article, comments } = useState(['article', 'comments']);
		fetch(props.articleId); // dispatch the "fetch" action

		return {
			// both are computed compositions for to the store
			article,
			comments
		}
	}
}

Typescript mappings

You can also supply typing information to each of the mapping functions to provide a fully typed mapping.

import { useState, useActions } from 'vuex-composition-helpers';

interface RootGetters extends GetterTree<any, any> {
	article: string;
	comments: string;
}

interface RootActions extends ActionTree<any, any> {
	fetch: (ctx: ActionContext<any, any>, payload: number);
}

export default {
	props: {
		articleId: String
	},
	setup(props) {
		const { fetch } = useActions<RootActions>(['fetch']);
		const { article, comments } = useGetters<RootGetters>(['article', 'comments']);
		fetch(props.articleId); // dispatch the "fetch" action

		return {
			// both are computed compositions for to the store
			article,
			comments
		}
	}
}

Advanced Usage Example

Consider separate the store composition file from the store usage inside the component. i.g.:

// store-composition.js:
import { wrapStore } from 'vuex-composition-helpers';
import store from '@/store'; // local store file

export default wrapStore(store);
// my-component.vue:
import { createNamespacedHelpers } from './store-composition.js';
const { useState, useActions } = createNamespacedHelpers('articles'); // specific module name
const { fetch } = useActions(['fetch']);

export default {
	props: {
		articleId: String
	},
	setup(props) {
		const { article, comments } = useState(['article', 'comments']);
		fetch(props.articleId); // dispatch the "fetch" action

		return {
			// both are computed compositions for to the store
			article,
			comments
		}
	}
}

Transpiling

It depends on you project's stack, but let's say it consists of webpack, babel and ts-loader.

The rule processing .ts files should whitelist vuex-composition-helpers. If your project uses a raw webpack installation, it should resemble this.

// webpack.config.js
module.exports = {
  ...
  module: {
    rules: [
      test: /\.ts$/,
      // If node_modules is excluded from the rule, vuex-composition-helpers should be an exception
      exclude: /node_modules(?!\/vuex-composition-helpers)/,
      use: [
        {
          loader: 'babel-loader',
          ...
        },
        {
          loader: 'thread-loader',
          options: { ... }
        },
        {
          loader: 'ts-loader',
          ...
        }
    ]
  }
}

When using vue-cli, use this instead

// vue.config.js
module.exports = {
  ...
  chainWebpack: config => {
    config
      .rule('ts')
      .include
      .add(/vuex-composition-helpers/)
  }
}

If your webpack configuration is excluding node_modules from the bundle, which is common for SSR, this library should be an exception.

// webpack.config.js
module.exports = {
 ...
  externals: [nodeExternals({
    whitelist: [/^vuex-composition-helpers/]
  })],
}

Babel should not exclude or ignore this library. If you use vue-cli, you may need the following configuration.

// vue.config.js
module.exports = {
  ...
  transpileDependencies: ['vuex-composition-helpers'],
}

Although it's not strictly required, maybe ts-loader needs to have allowTsInNodeModules enabled in your project. Finally check that this library is not excluded in tsconfig.json, and if it was necessary, put it in the include list.

Enjoy!

Comments
  • Allow a type interface on using methods

    Allow a type interface on using methods

    Just wanted to make a suggestion to allow for adding a typed interface to provide full typing for the use functions. I have things split out into an interface for actions, mutations, getters, and state of each module, but almost all of the Vuex Composition APIs drop typing and either emit Function or any despite the fact that I have fully typed interfaces for all of this.

    opened by Stoom 13
  • Add support of Vue 2.7

    Add support of Vue 2.7

    This uses vue-demi to determine if the imports needs to be done from vue or the @vue/composition-api plugin.

    Closes #71.

    Another solution would to bump the minimal supported version to Vue 2.7 and directly importing from vue but it will complicate upgrades because it means vue and vuex-composition-helpers needs to be bumped simultaneously.

    opened by LeSuisse 10
  • [Typescript] [next] UnwrapRef is not taken into consideration when destructuring result from useXXXX

    [Typescript] [next] UnwrapRef is not taken into consideration when destructuring result from useXXXX

    Hello,

    It seems like object destructuration is not taken into account correctly when destructuring from useXXX functions, despite being used as examples.

    A non nested computed value is unwrapped with the type Ref<UnwrapRef<T>>. https://v3.vuejs.org/guide/reactivity-fundamentals.html#ref-unwrapping

    Here is an example:

    setup() {
       const {count} = useState(['count']);
    
      return {
         count
      }
    },
    methods: {
        increment: function() {
          this.count.value++; //valid at compile time, but has runtime error
          this.count++; //doesn't compile, but correctly runs
       }
    }
    

    This is really bothersome, as I'm forced to not use destructuration, and go like this: this.rootState.count.value, which is so much longer than this.count

    opened by n-kogo 7
  • How can this library be integrated with jest?

    How can this library be integrated with jest?

    Hey!

    Thank you for your library! It's really helpful when you use vue composition api. However I am trying to find a way to test it properly. Currently jest raises an error for me:

        Jest encountered an unexpected token
    
        This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
    
        By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
    
        Here's what you can do:
         • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
         • If you need a custom transformation specify a "transform" option in your config.
         • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
        You'll find more details and examples of these config options in the docs:
        https://jestjs.io/docs/en/configuration.html
    
        Details:
    
        /Users/serj/Projects/Email_platform/node_modules/vuex-composition-helpers/src/index.ts:1
        ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './global'
                                                                                                 ^^^^^^
    
        SyntaxError: Unexpected token 'export'
    
          144 | <script lang="ts">
          145 | import { Ref, defineComponent, ref, computed, reactive } from "@vue/composition-api";
        > 146 | import { useGetters, useActions } from "vuex-composition-helpers";
              | ^
          147 | import { GetterTree, ActionTree, ActionContext } from "vuex";
          148 | import { ILanguageDirection, IMedia, IMediaForm, IMediaAttributes } from "../interfaces";
          149 | import useValidationState from "helpers/useValidationState";
    
          at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1059:14)
          at Object.<anonymous> (app/javascript/content_library/components/EditMediaModal.vue:146:1)
          at Object.<anonymous> (app/javascript/content_library/components/__tests__/EditMediaModal.spec.ts:17:1)
    

    My jest config:

    module.exports = {
      moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node", "vue"],
      modulePathIgnorePatterns: ["<rootDir>/.*/__mocks__"],
      setupFiles: ["<rootDir>/jest_setup.ts", "jest-date-mock"],
      moduleDirectories: ["node_modules", "<rootDir>/app/javascript"],
      transform: {
        "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
        ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
        "^.+\\.tsx?$": "ts-jest",
      },
      testRegex: "/__tests__/.*\\.(ts|tsx|js)$",
      transformIgnorePatterns: ["node_modules/(?!vee-validate/dist/rules)"],
      snapshotSerializers: ["<rootDir>/node_modules/jest-serializer-vue"],
      testPathIgnorePatterns: ["<rootDir>/app/assets", "<rootDir>/config/webpack/test.js", "<rootDir>/vendor"],
      moduleNameMapper: {
        "^@/(.*)$": "<rootDir>/app/javascript/$1",
        "\\.(css|less)$": "identity-obj-proxy",
        "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
          "<rootDir>/app/javascript/__mocks__/fileMock.js",
      },
      restoreMocks: true,
      globals: {
        "ts-jest": {
          tsConfig: "tsconfig.jest.json",
          babelConfig: true,
          diagnostics: false,
        },
      },
    };
    
    opened by Loremaster 7
  • Cannot transpile typescript module as a dependency

    Cannot transpile typescript module as a dependency

    This module distributes typescript source files by default. This doesn't integrate well in a setup using webpack, babel and ts-loader, even if allowTsInNodeModules is enabled, vuex-composition-helpers is not excluded in webpack and tsconfig includes the path of this module. The compilation ends "successfully", but the code is not transpiled.

    export * from './global'
    
    SyntaxError: Unexpected token export
    

    In #3 there is a mention about importing vuex-composition-helpers/dist. Unfortunately, typings are missing.

    Discussion about packaging practices of typescript projects

    opened by javiertury 7
  • Javascript packaging with typings

    Javascript packaging with typings

    Hi,

    My application is built with rollup and the current packaging didn't work. A npm package should reference a javascript file so it should reference the .js file and provide typings.

    I hope it still works with your projects

    opened by christphe 7
  •  Error in setup:

    Error in setup: "Error: You must use this function within the "setup()" method, or insert the store as first argument."

    I started a new nuxt project form scratch added nuxt-composition-api and vuex-composition-helpers package

    I get this error Error in setup: "Error: You must use this function within the "setup()" method, or insert the store as first argument." when trying to access store

    // index.vue
    
    <template>
      <div>
        {{ getLoadingState }}
      </div>
    </template>
    
    <script lang="ts">
    import { defineComponent, ref } from "@nuxtjs/composition-api";
    import { useNamespacedGetters } from "vuex-composition-helpers";
    
    export default defineComponent({
      name: "Index",
      setup() {
        const { getLoadingState } = useNamespacedGetters("loading", [
          "getLoadingState",
        ]);
        const nuts = ref("text");
    
        return {
          nuts,
          getLoadingState,
        };
      },
    });
    </script>
    
    
    // nuxt.config.ts
    
    buildModules: [
        // https://go.nuxtjs.dev/typescript
        "@nuxt/typescript-build",
        "@nuxtjs/composition-api/module",
      ],
    
    build: {
        transpile: ["vuex-composition-helpers"],
      },
    
    
    /store/loading/index.js
    
    export const state = () => ({
      loading: false,
    });
    
    export const getters = {
      getLoadingState: (state) => state.loading,
    };
    export const mutations = {
      setLoading(state, payload) {
        state.loading = payload;
      },
    };
    export const actions = {
      toggleLoading({ commit }, payload) {
        commit("setLoading", payload);
      },
    };
    
    "dependencies": {
        "@nuxtjs/axios": "^5.13.6",
        "@nuxtjs/composition-api": "^0.32.0",
        "core-js": "^3.19.3",
        "nuxt": "^2.15.8",
        "vue": "^2.6.14",
        "vue-server-renderer": "^2.6.14",
        "vue-template-compiler": "^2.6.14",
        "vuex-composition-helpers": "^1.1.0",
        "webpack": "^4.46.0"
      },
      "devDependencies": {
        "@nuxt/types": "^2.15.8",
        "@nuxt/typescript-build": "^2.1.0"
      }
    
    
    opened by rafaelmagalhaes 6
  • WIP dropped composition API, adjustements to Vue3

    WIP dropped composition API, adjustements to Vue3

    Related to https://github.com/greenpress/vuex-composition-helpers/issues/25

    Still WIP, some tests are failing when comparing rendered templates

    Also, I had to add {immediate: true} to all watch() calls in tests, because it looked like the right thing to do. Is it correct @davidmeirlevy?

    opened by Valian 6
  • Getters not working

    Getters not working

    Action and State helpers appear to work per the documentation, but getters fail with

    [Vue warn]: Error in v-on handler: "TypeError: isShowing is not a function"

    Question is, what am I doing wrong/misundestanding from the docs?

    Details: the SFC is nothing more than a button, with @click="toggle() and this script:

      import { ref, computed } from '@vue/composition-api';
      import { createNamespacedHelpers } from 'vuex-composition-helpers/dist';
      const { useState, useActions, useGetters } = createNamespacedHelpers('sidebar');
      // import { useState, useGetters, useActions } from 'vuex-composition-helpers/dist';
    
      export default {
        setup(props, context) {
          const { showing } = useState(['showing']);
          const { isShowing } = useGetters(['isShowing']);
          const { setShowing } = useActions(['setShowing']);
    
          function toggle() {
            setShowing(!isShowing());  // <-- line where the error occurs
            console.log('app-bar: toggle=' + isShowing());
          }
    
          return {
            showing,
            isShowing,
            toggle,
          };
        },
      };
    

    Using a standard modular store; tested & currently working under Vue 2. Module is 'sidebar.js'

    const state = {
      showing: false,
    };
    const getters = {
      isShowing: (state) => {
        console.log('sb: isShowing=' + state.showing);
        return state.showing;
      },
    };
    const actions = {
      setShowing: ({ commit }, val) => {
        console.log('sb: setShowing=' + state.showing + '->' + val);
        commit('changeShowing', val);
      },
    };
    const mutations = {
      changeShowing: (state, val) => {
        state.showing = val;
      },
    };
    export default {
      namespaced: true,
      state,
      getters,
      actions,
      mutations,
    };
    
    
    opened by grosenberg 6
  • Vuex official mappers

    Vuex official mappers

    Question

    Hi, in my project we use vuex mappers in a way:

    ...mapActions('user', ['resetPassword']),

    Is it possible to achieve that with your library? Basically I want to be able to use: mapActions(module: String, actions: [])

    Proposal

    I made a small wrapper for traditional mappers:

    export function useActions(...args) {
      const appContext = { $store: useStore() };
      const mappedActions = mapActions(...args); //vuex mapper
      const mappedActionsContext = mapValues(mappedActions, el => el.bind(appContext));
    
      return mappedActionsContext;
    }
    

    And then usage: const storeActions = useActions('user', ['resetPassword']);

    It's very tested yet, but seems to work fine. The same for getters:

    export function useGetters(...args) {
      const appContext = { $store: useStore() };
      const contextMapGetters = mapGetters.bind(appContext);
      const mappedGetters = contextMapGetters(...args);
      const mappedGettersContextValues = mapValues(mappedGetters, el => el.bind(appContext));
      // wrap everything in refs, the only way to keep it reactive
      const refs = mapValues(mappedGettersContextValues, val => computed(val));
    
      return refs;
    }
    
    opened by krystian50 6
  • A problem occurred in v-for.

    A problem occurred in v-for.

    hi.

    In the composition API of vue, there is no helper method of vuex, so while searching, I found your library and found an error in the following situation.

    I was able to get a ComputedRefImpl object by receiving useState() from createNamespacedHelpers(). ComputedRefImpl object was bidding to