美文网首页
vuex入门

vuex入门

作者: 藕藕藕汀 | 来源:发表于2018-06-05 18:02 被阅读14次

    1.入门使用

    (1)引入vuex

    $npm install vuex --save
    

    (2)新建src/vuex文件夹,在vuex中新建store.js文件。文件中引入vue和vuex。

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    //通过Vue.use()进行引用
    Vue.use(Vuex);
    

    (2)初步使用
    store.js添加一个常量对象,

    const state = {
        count:1,
    }
    

    export出去,让外部可以引用

    export default new Vuex.Store({
        state
    })
    

    新建src/components/count.vue,模板中引入store.js,并用{{$store.state.count}}输出store.js中count的值。

    <template>
        <div>
            <h2>{{msg}}</h2>
            <h3>{{$store.state.count}}</h3>
            <hr>
        </div>
    </template>
    
    <script>
    import store from '@/vuex/store';
    export default {
        data(){
            return {
                msg:"Hello Vuex"
            }
        },
        store
    }
    </script>
    

    以上,在App.vue中<router-link>到count.vue页面中,成功显示了store.js的count值。
    在store.js中增加两个方法改变state中count的值。

    const mutations={
        add(state){
            state.count++;
        },
        reduce(state){
            state.count--;
        }
    }
    

    在export出的增加mutations

    export default new Vuex.Store({
        state,
        mutations
    })
    

    在count.vue模板中增加两个button,调用store中mutations的方法控制count值的加减。

    <div>
        <button @click="$store.commit('add')">+</button>
        <button @click="$store.commit('reduce')">-</button>
    </div>
    

    以上实现了vuex的初次使用,对count值的改变。

    2.state

    store.js中state值赋值给模板中的展示值。

    (1)通过computed的计算属性直接赋值
    computed:{
            count(){
                return this.$store.state.count;
            }
        }
    

    修改count.vue中count展示方式

    <h3>{{$store.state.count}}---{{count}}</h3>
    
    (2)通过mapState的对象赋值

    引入mapState

    import {mapState} from 'vuex';
    

    在computed计算属性里为count赋值

    computed:mapState({
            count:state => state.count
        })
    

    (3)通过mapState的数组赋值
    同样要引入mapState,然后在computed中做设置

    computed:mapState(["count"])
    

    3.Mutations

    (1)修改状态

    修改mutations中add方法,添加一个参数n。

    const mutations={
        add(state,n){
            state.count += n;
        },
        reduce(state){
            state.count--;
        }
    }
    

    修改count.vue中$store.commit的传参。

    <div>
         <button @click="$store.commit('add',10)">+</button>
         <button @click="$store.commit('reduce')">-</button>
    </div>
    

    浏览器中count每次增加10。

    (2)修改$store.commit()成@click=""的形式

    在count.vue中import入mapMutations

    import {mapState, mapMutations} from 'vuex';
    

    在count.vue中的methods属性中加入mapMutations

    methods:mapMutations([
           'add','reduce' 
        ])
    

    在模板中直接使用@click=""

    <div>
          <button @click="add(10)">+</button>
          <button @click="reduce">-</button>
    </div>
    

    4.getters

    数据获取之前对数据进行过滤和加工。

    (1)getters基本用法

    在store.js中用const声明getters属性

    const getters = {
        count:function(state){
            return state.count += 100;
        }
    }
    

    并export出

    export default new Vuex.Store({
        state,
        mutations,
        getters
    })
    

    count.vue中配置computed属性

    computed:{
            ...mapState(["count"]),
            count(){
                return this.$store.getters.count;
            }
        },
    
    (2)用mapGetters简化

    count.vue中import引入mapGetters

    import {mapState, mapMutations, mapGetters} from 'vuex';
    

    修改computed属性,mapGetters

        computed:{
            ...mapState(["count"]),
            ...mapGetters(["count"])
        },
    

    5.actions

    在actions中提交mutation,将mutations里面处理数据的方法编程可异步处理数据的方法(通过mutation来操作)。
    在store.js中声明actions

    const actions = {
        addAction(context){//context:上下文,可以理解成store.js本身
            context.commit('add',10)
        },
        reduceAction({commit}){//一般简写成直接把commit对象传递过来
            commit('reduce')
        }
    }
    

    同样要export导出

    export default new Vuex.Store({
        state,
        mutations,
        getters,
        actions
    })
    

    在count.vue模板中使用

    methods: {
          ...mapMutations([
            'add', 'reduce'
          ]),
          ...mapActions(['addAction','reduceAction'])
        },
    
    //增加了一组增减button
        <div>
          <button @click="addAction">+</button>
          <button @click="reduceAction">-</button>
        </div>
    

    以上在浏览器中可以增减count的值
    增加异步效果

    const actions = {
        addAction(context){
            context.commit('add',10);
            setTimeout(()=>{context.commit('reduce')},3000);
            console.log('我比reduce提前执行');
        },
        reduceAction({commit}){
            commit('reduce')
        }
    }
    

    在浏览器中可以看到,点击增加button之后,count增加,之后控制台先打印出'我比reduce提前执行',然后才会减少1。

    6.module

    状态管理器的模块组。
    如果项目比较复杂,那state是一个很大的对象,store对象也将会变得非常大,难于管理。
    module可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。
    在store.js中声明模块组

    const moduleA = {
        state,mutations,getters,actions
    }
    

    修改export出的Vuex.Store里的值

    export default new Vuex.Store({
        modules:{a:moduleA}
    })
    

    在count.vue中使用

    <h3>{{$store.state.a.count}}</h3>
    

    同样可以简化方法,在computed中设置

    computed: {
          count(){
              return this.$store.state.a.count;
          }
        }
    
    <h3>{{count}}</h3>
    

    store.js中有多个模块组的结构

    const moduleA = {
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
     }
    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
     }
    
    const store = new Vuex.Store({
      modules: {
        a: moduleA,
        b: moduleB
    })
    

    相关文章

      网友评论

          本文标题:vuex入门

          本文链接:https://www.haomeiwen.com/subject/ozcysftx.html