vue状态管理 —— vuex简单使用

先来一张vuex官方的流程图:

vuex流程理解:

vuex中包括的对象有:state、mutations、actions、getters和modules。

在vuex流程中设及到的对象:Components、Actions、Mutations和State。

实现过程:

用户在component中通过操作dispatch触发了一个action,action就会commit一个mutation函数,从而mutate一个新的state,vuex就会将新的state渲染(render)到component中,从而让界面更新。

实际使用(代码):

1. main.js中引入vuex并定义Store:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

let store = new Vuex.Store({
  state: {
    allPrice : 0 
  },
  mutations: {    //定义mutations
    add(state, price){      //加
      state.allPrice += price;
    },
    jian(state, price){     //减
      state.allPrice -= price;
    }
  },
  actions:{     //定义action,commit触发定义mutations
    increase(contxt, price){        //commit触发add这个mutations
      contxt.commit('add', price);
    }
  },
  getters: {    //定义getters
    grtStorePrice: state => {     //定义grtStorePrice这个getters;必须return一个值
      return state.allPrice + "元";
    }
  }

});


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

2. 页面中调用store中的state、mutations、actions和getters:

<template>
    <div id="storeDemo">
        <!--$store.state.allPrice 调用(显示)store中的state里面的 allPrice -->
        <p>store使用   总价:{{$store.state.allPrice}}</p>         
         <!--$store.getters.grtStorePrice 调用(显示)store中的getters里面的定义的 grtStorePrice -->
        <p>getters使用   总价:{{$store.getters.grtStorePrice}}</p>          
        <p class="btn"> 
            <span @click="minus">-</span>
            <span @click="add">+</span>
        </p>
    </div>
</template>
<script>
export default {
    name:'StoreDemo',
    data(){
        return{
            price : 5,
        }
    },
    methods: {
        add(){
            // this.$store.commit('add',this.price);
            this.$store.dispatch('increase',this.price);      //通过dispatch触发action,从而触发mutations
        },
        minus(){
            this.$store.commit('jian',this.price);          //不通过action触发mutations,即自己直接commit触发mutations
        }
    }
}
</script>
<style lang="scss" scoped>
    #storeDemo{
        width: 500px;
        height: 300px;
        // background: #fcc;
        padding: 20px;
        .btn{
            span{
                display: inline-block;
                width: 50px;
                border: solid 1px #ccc;
                cursor: pointer;
                margin-top: 20px;
            }
        }
    }
</style>


注意:

this.$store.state 主要用于获取store中的state;

this.$store.getters 主要用与获取store中处理过的state(相当于调用了computed的数据);

3.vuex的Modules对象:主要用于store分模块

4. 最后:来个页面效果(比较简单)

个人觉得vuex和redux的概念差不多:

redux流程:用户在component中dispatch一个action,store就会自动触发一个redrcers,redrcers会接受两个参数(旧state,antion)并根据action的type属性得到一个新的state(注意:redrcers是一个纯函数);store得到新的state后会调用用户定义的监听函数,从而更新component。

redux可以去学习阮大神的教程:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!

猜你喜欢

转载自blog.csdn.net/halo1416/article/details/81285917