深入浅出vuex

对于vuex,就像rudux的作者所说的”您自会知道什么时候需要它
为了理解vuex,demo中运用了vuex来对底部Icon进行变化。

Vuex

Vuex是专门为 Vue.js 设计的状态管理库

如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。

首先是创建一个 store ,里面有:

  • state(状态)
  • mutations(引发状态改变的方法)
  • actions(触发mutations的方法)

这里写图片描述
然后在每次对数据对象进行操作的时候,进行commit(mutations 的方法名)用来触发mutations的方法来改变state状态.. 同时我们进行dispatch(action 的方法名)用来触发mutations的方法来改变state状态..

vue的组件中都有computed,当state改变的时候会触发computed,所以我们就可以根据state的值,对页面进行修改。

  • 先声明一个Store:
const vuex_store = new Vuex.Store({
  state: {
     index:1
  },
  mutations: {
        ADD_INDEX(state) {
        state.index++;
    },
  },
  actions:{
    addIndex({commit}) {
        commit('ADD_INDEX')
    },  
  }
})
  • 然后在组件中写触发mutation:
    this.$store.commit('ADD_INDEX') 这样就可以从组件中修改state的值。

  • 如果想要在组件中监听state的变化,来动态改变一些值:

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

    <h1>{{index}}</h1>

  • 同时我们也可以通过action,来触发mutation的方法来改变状态。
    this.$store.dispatch("addIndex");

猜你喜欢

转载自blog.csdn.net/qq_24073885/article/details/70242704