All Projects → galvez → Vue Stator

galvez / Vue Stator

Vuex alternative based on Vue.observable()

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Vue Stator

Nuxt Elm
基于nuxt2+vue构建的全栈开源项目
Stars: ✭ 304 (+87.65%)
Mutual labels:  nuxt, vuex
Hackernews
HackerNews clone built with Nuxt.js
Stars: ✭ 758 (+367.9%)
Mutual labels:  nuxt, vuex
Nuxt Firebase Sns Example
Nuxt v2 & Firebase(Hosting / Functions SSR / Firestore), Google Auth SNS Example.
Stars: ✭ 485 (+199.38%)
Mutual labels:  nuxt, vuex
Intro To Vue
Workshop Materials for my Introduction to Vue.js Workshop
Stars: ✭ 2,668 (+1546.91%)
Mutual labels:  nuxt, vuex
Vuex Orm Examples Nuxt
The example Nuxt application to demonstrate the use case of the Vuex ORM.
Stars: ✭ 63 (-61.11%)
Mutual labels:  nuxt, vuex
Vuemmerce
👉 Responsive ecommerce template 🛒 built with Vue.js and Nuxt.js
Stars: ✭ 223 (+37.65%)
Mutual labels:  nuxt, vuex
Vuecnodejs
⚽️🎉Vue初/中级项目,CnodeJS社区重构。( a junior project of Vue.js, rewrite cnodejs.org ) 预览(DEMO):
Stars: ✭ 705 (+335.19%)
Mutual labels:  nuxt, vuex
Typed Vuex
🏦 A typed store accessor for vanilla Vuex.
Stars: ✭ 193 (+19.14%)
Mutual labels:  nuxt, vuex
Laravel Vuejs.com
Laravel and VueJs Blog, using Laravel nova, GraphQL, NuxtJs, Apollo and ...more
Stars: ✭ 54 (-66.67%)
Mutual labels:  nuxt, vuex
Nuxt.js
The Intuitive Vue(2) Framework
Stars: ✭ 38,986 (+23965.43%)
Mutual labels:  nuxt, vuex
Nuxt Juejin Project
仿掘金web网站,使用服务端渲染。主要技术:nuxt + koa + vuex + axios + element-ui 。
Stars: ✭ 209 (+29.01%)
Mutual labels:  nuxt, vuex
Surmon.me
🆒 My personal website and blog, powered by @vuejs (3)
Stars: ✭ 1,767 (+990.74%)
Mutual labels:  nuxt, vuex
Buefy Shop
A sample shop built with Nuxt, Stripe, Firebase and Serverless Functions
Stars: ✭ 207 (+27.78%)
Mutual labels:  nuxt, vuex
Vue Kindergarten
Modular security for Vue, Vuex, Vue-Router and Nuxt
Stars: ✭ 303 (+87.04%)
Mutual labels:  nuxt, vuex
Vue Org Chart
Manage and publish your interactive organization chart (orgchart), 100% free and no install required: just copy a folder to any location
Stars: ✭ 207 (+27.78%)
Mutual labels:  nuxt, vuex
Nuepress
📖 Nuxt.js + WordPress REST API
Stars: ✭ 524 (+223.46%)
Mutual labels:  nuxt, vuex
Vue Gates
🔒 A Vue.js & Nuxt.js plugin that allows you to use roles and permissions in your components or DOM elements, also compatible as middleware and methods.
Stars: ✭ 184 (+13.58%)
Mutual labels:  nuxt, vuex
Vue Cheatsheet
Modified version of the official VueMastery cheatsheet
Stars: ✭ 188 (+16.05%)
Mutual labels:  nuxt, vuex
Nuxt Ssr Demo
✨ 高仿掘金,整合 vue + nuxt + axios + vuex + vue-router (nuxt 自带 vuex 和 vue-router),一个基于 Nuxt 的服务器端渲染 Demo
Stars: ✭ 856 (+428.4%)
Mutual labels:  nuxt, vuex
Nuxt Api Example
Nuxt.js API Example using Vuex and axios
Stars: ✭ 118 (-27.16%)
Mutual labels:  nuxt, vuex

vue-stator

npm version npm downloads Circle CI Codecov

A lightweight, nearly drop-in replacement for Vuex.

npm i vue-stator --save

See documentation for Vue.js or Nuxt.js.

Stator is the stationary part of the rotary system - thanks to @pimlie for the awesome name suggestion.

No more mutations

vue-stator uses Vue.observable() under the hood, which means assignments and Array changes will automatically trigger updates. So instead of actions and mutations, vue-stator only lets you define actions. To make transition from Vuex easy, it introduces a new function signature for actions that help making them look like mutations if needed.

Say you have a store/actions.js file defining global actions:

export function myAction ({ state, actions }, param) {
  state.param = param // mutates!
  actions.otherAction()
}

export function otherAction ({ state }, param) {
  state.paramDoubled = param * 2 // mutates!
}

The first argument is the local module context, the store object itself (and root state/getters/actions) is accessible from the this value within the action. This means that if you need to access the global $state, $actions or $getters you can access them using eg this.$state

Unified state and modularization

vue-stator introduces the possibility of having a unified state object. Instead of shuffling across subdirectories looking for different state definitions, you could now have a single place to look at: store/state.js.

Still, the ability to group actions and getters by a key is convenient. vue-stator fully supports module syntax which can define their own state, getters and/or actions.

In practice, this just means you can define module actions where the first argument is a context object containing:

  • state: the state for the current vue-stator module or the root state
  • getter: the getters for the current vue-stator module or the root getters
  • actions: the actions for the current vue-stator module or the root actions
import { plugin as VueStator } from 'vue-stator'

Vue.use(VueStator, {
  state: () => ({
    rootKey: 'a',
    auth: {
      user: null,
      loggedIn: false
    }
  }),
  modules: {
    auth: {
      actions: {
        login ({ state }, user) {
          state.user = user
          state.loggedIn = false

          this.$state.rootKey = 'b'
        }
      }
    }
  }
}

Again notice how state is a direct reference to $state.auth, to recap:

  • The state property of the first argument is the state key that matches the module namespace
  • this.$state is the the root state

In Nuxt.js if you need to access properties from the Nuxt content (e.g. $axios or $http), then you need to provide the inject module option in your nuxt.config. See our Nuxt.js docs for more information

Beware: in Vuex, dispatching actions will always return a Promise.

In vue-stator, that's optional. If you have code that expects an action to return a Promise (by following it with .then(), for instance), make sure to return Promise.resolve() instead. Or, you can also simply switch to async/await syntax and it will work just fine.

Vue Devtools

vue-stator also has vue devtools integration. You can pass devtools: false as store option if you want to disable this. By default the value of Vue.config.devtools is used (which is false in production)

Due to differences between Vuex and vue-stator there are some remarks:

  • reverting to a previous state doesnt reset newly added keys after that state
  • getters are shown as an object tree of the modules you use

Vuex-like helpers

import { mapState, mapActions, mapGetters } from 'vue-stator'

vue-stator packs mapState, mapActions and mapGetters, which accept a dictionary of method mappings, eg (['method', 'module/namespace/method'])

You have access to everything directly in Vue's context though.

That is, you can just reference $state.something in your Vue template and it'll work.

statorMap component option

You can enable a mixin helper by passing { mixin: true } to your plugin options. Instead of calling mapState etc in your components you can now just add a statorMap option in your component:

// App.vue
Vue.use(VueStator, { mixin: true })

// my-component.vue
<script>
export default {
  statorMap: {
    // omitting the namespace is the default behaviour
    // set this to false if you dont want to omit the namespace,
    // then the properties will be available as: this['my/module/nonAliasedKey']
    //omitNamespace: true,
    state: {
      my: {
        module: {
          nonAliasedKey: true,
          aliasedKey: 'theModuleKey'
        }
    },
    getters: [
      'rootGetter',
      'my/module/myGetter'
    ],
    actions: ['myAction']
  },
  mounted () {
    this.nonAliasedKey
    this.aliasedKey
    this.rootGetter
    this.myGetter
    this.myAction()
  }
}
</script>

You can also use a function for statorMap in case you need to eg map different state for eg Server-side or Client-side

  statorMap() {
    if (process.client) {
      return { ... }
    }
    return { ... }
  }

Runtime helpers

vue-stator also provides some helper methods to interact with the store more easily.

  • $stator.subscribe('module/key', callback) To quickly subscribe to specific state updates. This uses Vue.$watch under the hood

  • $stator.registerModule(module, moduleName) To dynamically register a store module. The moduleName can be ommitted if your module already contains a name property

  • $stator.unregisterModule(moduleName) To dynamically unregister a store module

  beforeCreate () {
    this.$stator.registerModule({
      name: 'my/module',
      state () {
        return {
          key: true
        }
      }
    })

    // or

    this.$stator.registerModule({
      state () {
        return {
          key: true
        }
      }
    }, 'my/module')
  },
  mounted () {
    this.$state.my.module.key // true
  },
  destroyed () {
    this.$stator.unregisterModule('my/module')
  }

Getters

In a further effort to make transition from Vuex, modularized getters are available in a similar fashion. The arguments passed to getter functions have the exact same signature as Vuex.

import { plugin as VueStator } from 'vue-stator'

Vue.use(VueStator, {
  state: () => ({
    user: {
      firstName: 'John',
      lastName: 'Doe'
    },
  }),
  modules: {
    user: {
      getters: {
        isFirstNameValid: state => state.firstName.length > 0,
        isLastNameValid: state => state.lastName.length > 0,
        isValid: (_, getters) => getters.isFirstNameValid && getters.isLastNameValid,
        fullName (state, getters, rootState, rootGetters) {
          if (getters.isValid) {
            return `${state.firstName} ${state.lastName}`
          }

          /* below is for example purposes only, you dont need to use the root keys here */
          if (rootGetters.user.isFirstNameValid) {
            return rootState.user.firstName
          }

          return state.lastName
        }
      }
    }
  }
}

Storage helpers

If you need your state to always be comitted to a storage provider, vue-stator provides a configuration option which will automatically store and restore that state on changes

const statorConfiguration = {
  storage: {
    provider: {
      getItem (key) {
        // do something
      },
      setItem (key, value) {
        // do something
      }
    },
    namespaces: [
      'key',
      'module/key'
    ]
  }
}

Or if you need to use multiple storage providers

const statorConfiguration = {
  storage: [
    { // object syntax
      provider () {
        if (process.client) {
          return window.localStorage
        }
      },
      namespaces: [
        'persistent-key',
        'my/module/key'
      ]
    },
    [ // array syntax
      window.sessionStorage, // this will probably fail on SSR, see object syntax
      [ 'temp-key' ]
    ]
  ]
}

Nuxt.js module

Nuxt v2.10+ is required unless you set the module option baseDir to something different then store

Using vue-stator with Nuxt.js is as easy as using it with Vuex: a store will be automatically created by loading files placed in a conventional locations, such as store/state.js.

See full documentation for the Nuxt.js module here.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].