Vuex Composition Modules

Build Status downloads codecov code style: prettier

This project allows for experimental use of Vuex 5 composition API in Vue 3 .

Table of Contents

Getting started

  1. Install vuex

    import { createApp } from 'vue'
    import { createVuex } from 'vuex-composition-api'
    const vuex = createVuex()
    
    const app = createApp(App).use(vuex)
    // ...
  2. Define store/stores

    import { defineStore } from 'vuex-composition-api'
    export const counterStore = defineStore('counter', () => {
      const value = ref(0)
    
      function increment() {
        value.value++
      }
    
      return { value, increment }
    })
  3. Use store

    <template>
      <h1>Counter value: {{counter.value}}</h1>
      <button @click="counter.increment">INCREMENT</button>
    </template>
    
    <script lang="ts">
      import { definecComponent } from 'vue'
      import { useStore } from 'vuex-composition-api'
      import { counterStore } from './counter'
    
      export default definecComponent({
        setup() {
          const counter = useStore(counterStore)
    
          return {
            counter,
          }
        },
      })
    </script>

Composing

import { defineStore } from 'vuex-composition-api'
import { authStore } from './auth'

export const user = defineStore('user', ({ use }) => {
  const auth = use(authStore)

  function login(login, password) {
    auth.user(login, password)
  }

  return { login }
})

Plugins

  1. Create plugin

    function axiosPlugin(provide) {
      provide('axios', axios)
    }
  2. Install plugin

    import { createApp } from 'vue'
    import { createVuex } from 'vuex-composition-api'
    
    const vuex = createVuex({ plugins: [axiosPlugin] })
    
    const app = createApp(App).use(vuex)
    //...
  3. Use plugin

    import { defineStore } from 'vuex-composition-api'
    
    export const authStore = defineStore('auth', ({ axios }) => {
      function user(login, password) {
        axios.post('/login', {
          login,
          password,
        })
      }
    
      return { login }
    })

API

defineStore

function defineStore(name: string, setup: StoreSetup): Store

createVuex

interface Vuex {
  install(app: App): App
  store(store: Store): T
}

function createVuex(options: { plugins: Plugin[] }): Vuex

useStore

function useStore(storeOptions: Store): T