Vuex 拾遗

引入Vuex的目的:为众多的Vue组件提供一个全局管理共享组件状态的控制中心,当一个共享状态改变时,能使调用该共享状态的组件得到更新。并且使用Vuex的API,每个共享状态的改变都能被追踪。

组件如何引入Vuex:

组件在实例化时,通过store选项引入Vuex的共享变量。之后组件通过this.$store.someprops.subprops访问共享变量

Vuex 通过 store 选项,提供了一种机制将状态从根组件『注入』到每一个子组件中(需调用 Vue.use(Vuex)):

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})

组件的重构为使用Vuex的方式,需要作出的改变:

1、将组件从data获取数据的方式改为计算属性去处理。

computed:{
   shareData(){
       return this.$store.state.shareData  
    }  
}

Vuex 四大关键词:state,getters,mutations, actions

state:基本的共享状态定义,组件通过this.$score.state.props访问,有简化方法mapState;

getters:适用于对state进行计算,组件通过this.$score.getters.props访问,有简化方法mapGetters;

mutations:用来改变state的状态,由state.commit('mutationtype')调用,只能用同步方法,有简化方法mapMutations;

 actions:解决mutations不能用异步方法的缺陷,其提供了context参数,通过context.commit,context.dispatch触发mutations,或者通过 context.state 和 context.getters 来获取 state 和 getters,有简化方法mapActtions

备注:还有一个modules参数,支持将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

栗子:

// make sure to call Vue.use(Vuex) if using a module system

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
  	increment: state => state.count++,
    decrement: state => state.count--
  }
})

new Vue({
  el: '#app',
  computed: {
    count () {
	    return store.state.count
    }
  },
  methods: {
    increment () {
      store.commit('increment')
    },
    decrement () {
    	store.commit('decrement')
    }
  }
})

  

原文地址:https://www.cnblogs.com/linyihai/p/7142031.html