使用ES6 class来编写vuex模块,使得代码更易于维护和拓展

4,148 阅读1分钟
原文链接: github.com

vuex-class.js

Coverage Status Build Status npm npm npm

Use es6 class to write the vuex module, making the code easier to maintain and expand.

Installing

npm install vuex-class.js --save

Document

Example

import Vue from 'vue'
import Vuex from 'vuex'
import VuexClass from 'vuex-class.js'

Vue
  .use(Vuex)

class MyStoreRoot extends VuexClass {
  constructor () {
    super()
    this.strict = process.env.NODE_ENV !== 'production'
    this.state = {
      count: 0
    }
    // Note: the submodule does not have the bugins option
    this.plugins = [
      VuexClass.init()
    ]
    this.modules = {
      chlid: new Chlid()
    }
  }
  // mutations
  set setCount (count) {
    this.state.count = count
  }
  // getters
  get countText () {
    return `text:${this.state.count}`
  }
  // actions
  clickCount () {
    setTimeout(() => {
      // Two methods to submit mutation
      // 1、Direct assignment
      // this.setCount = 1000
      // 2、Call method, note: if there is a get setCount attribute on class, this method does not exist.
      // this.setCount(1000)
    })
  }
}

class Chlid extends VuexClass {
  constructor () {
    super()
    this.state = {
      isBtn: false
    }
    this.namespaced = true
  }
  set switchBtn (payload) {
    this.state.isBtn = !this.state.isBtn
  }
  get text () {
    return this.state.isBtn ? 'true' : 'false'
  }
}

const myStoreRoot = new MyStoreRoot()
const store = new Vuex.Store(myStoreRoot)

console.log(myStoreRoot.countText) // text:0
console.log(myStoreRoot.modules.chlid.text) // false

myStoreRoot.setCount = 666
myStoreRoot.modules.chlid.switchBtn()
console.log(myStoreRoot.countText) // text:666
console.log(myStoreRoot.modules.chlid.text) // true

License

MIT