【vuex学习】vuex基本使用及模块拆分

1.vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 

我认为vuex主要分为以下几个模块:

  • state  状态 
  • mutations  vuex的methods
  • actions   vuex的异步methods
  • getters  vuex的状态处理
  • modules  vuex的模块划分
  • 辅助函数  ...map*   vuex的映射(方便直接使用vuex中的数据和方法)
  • mutations_type   暂不知 

2.安装

npm install vuex --save

3.state (状态)

 state是vuex的核心,所有vuex中的操作都围绕state展开,但也是最简单的,因为state仅仅只是一个定义数据的地方。对于我们而言,一般情况下,state只有两个操作:

1.定义存储的数据结构

2.取出state中的数据

export default new Vuex.Store({
    // state相当于vue组件中的data,专门用来存放全局的数据
    state:{
       userInfo:{
           token:'',
           user:{}
       }
    }
});

4.getters

 上面讲了数据的定义,所以先说数据的处理(获取)。开始不清楚getters的时候,从很多人口中得知getters是过滤数据的操作。我:???

 我觉得也算是数据的过滤,但顾名思义,我更喜欢理解为数据的获取,只是这个获取过程中对state中的数据进行了处理(过滤)

比方说,我只需要上述userInfo中的token,那么可以通过getters只获取token的数据:

export default new Vuex.Store({
    state:{
       userInfo:{
           token:'',
           user:{}
       }
    },
    // getters相当于组件中的computed,getters是全局的,computed是组件内部使用的
    getters:{
      getToken(state) {
         //通过形参state来得到state中的数据进行处理
         return state.userInfo.token;
      }
   }
});

 页面中使用:

<template>
  <div class="home">
    <h2>{
   
   {$store.getters.getToken}}</h2>
  </div>
</template>

5.mutations

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。说白了,就是一个改变state中存储的数据的地方。

export default new Vuex.Store({
    state:{
       userInfo:{
           token:'',
           user:{}
       }
    },
    // getters相当于组件中的computed,getters是全局的,computed是组件内部使用的
    getters:{
      getToken(state) {
         //通过形参state来得到state中的数据进行处理
         return state.userInfo.token;
      }
    },
    // mutations相当于组件中的methods,但不能使用异步方法(定时器、axios等)
    mutations:{
        //data就是外界传过来的修改数据
        setUserInfo(state,data){
            state.userInfo = data;
        }
    }
});

 页面中使用:

<template>
    <div>
        <button @click="$store.commit('setUserInfo', '')">设置用户数据</button>
    </div>
</template>

 6.actions

actions是store中专门用来处理异步的,实际修改状态值的,还是mutations 。说白了,actions最多就是用来定义异步的拿数据或是处理数据的方法。

export default new Vuex.Store({
    state:{
       userInfo:{
           token:'',
           user:{}
       }
    },
    // getters相当于组件中的computed,getters是全局的,computed是组件内部使用的
    getters:{
      getToken(state) {
         //通过形参state来得到state中的数据进行处理
         return state.userInfo.token;
      }
    },
    // mutations相当于组件中的methods,但不能使用异步方法(定时器、axios等)
    mutations:{
        //data就是外界传过来的修改数据
        setUserInfo(state,data){
            state.userInfo = data;
        }
    },
   // actions专门用来处理异步,实际修改状态值的,依然是mutations
   actions:{
        login({commit},data){
            return this._vm.$api.user.login(data).then(res => {
                if(res.data.token){
                   //最终还是使用mutations的方法来修改数据
                   commit('setUserInfo',res.data);
                }
                return res;
            })
        }
    }
});

  页面中使用:

<template>
    <div>
        <button @click="$store.dispatch('login',form)">调用登录方法</button>
    </div>
</template>

 7.辅助函数 (...map* 系列函数)

 辅助函数一般有mapState,mapGetters,mapMutations,mapActions。

mapState和mapGetters在组件中都是写在computed里面

mapMutations和mapActions在组件中都是写在methods里面

mapState和mapGetters在页面上的使用:

<template>
	<div>
        //像vuex选项中其他属性一样,直接在页面上使用
        <h2>{
   
   {userInfo}}</h2>
        <h2>{
   
   {getToken}}</h2>
    </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'

export default {
  computed: {
    ...mapState(['userInfo'])
    ...mapGetters(['getToken'])
  }
}
</script>

mapMutations和mapActions在页面上的使用:

<template>
	<div>
        <button @click="setUserInfo('')">提交用户数据</button>
        <button @click="login(form)">触发登录方法</button>
    </div>
</template>

<script>
import { mapMutations, mapActions } from 'vuex'

export default {
  methods: {
       ...mapMutations(['setUserInfo']),
       ...mapActions(['login'])
   }
}
</script>

 8.modules

 modules就是用来将state拆分为多个,便于管理。很多人说如果项目不大的话就不用使用modules。这个。。。项目大小挺玄学的,我就要用 :)

 在实际的应用上,我觉得本文从这里开始才有用。

示例,假设我拆分出一个user模块,专门处理用户相关的数据:

目录结果如下:

store----

            modules----

                              user.js

                             xxx.js(后续还可以拆分出别的模块)

            index.js

user.js中:

export default {
    //限定在当前模块的命名空间中,可以使用点语法点该文件名来操作数据和方法
    namespaced:true,
    state:{
        userInfo:{
            token:'',
            user:{
    
            }
        }
    },
    mutations:{
        setUserInfo(state,data){
            state.userInfo = data;
        }
    },
    actions:{
        login({commit},data){
            return this._vm.$api.user.login(data).then(res => {
                if(res.data.token){
                   commit('setUserInfo',res.data);
                }
                return res;
            })
        }
    },
    getters:{
        getToken(state) {
            return state.userInfo.token;
        }
    }
};

 外部的index.js中:

import Vue from 'vue';
import Vuex from 'vuex';
//引入user模块
import user from './modules/user';
import xxx from './modules/xxx';

Vue.use(Vuex);


//导出store
export default new Vuex.Store({
  modules: {
    user,
    xxx(后续可添加模块)
  }
})

模块化后在页面上的使用:

<template>
	<div>
        //使用文件名user来获取state
        <h2>{
   
   {$store.state.user.userInfo.token}}</h2>
    </div>
</template>

<script>
import { mapActions,mapMutations } from 'vuex';
export default {
   methods:{
       login(){
          //因为使用了namespaced:true,所以通过user/login来区分方法
          //action通过dispatch来调用,如果是mutation则通过commit来提交
          this.$store.dispatch('user/login',this.form).then(res => {})
       },
       //同理使用了namespaced:true,辅助函数也应该标识是哪个空间的方法
       ...mapActions({'getMenu':'user/getMenu'}),
       ...mapMutations({'setMenu':'user/setMenu'})
   }
}
</script>

 我对mutations_type的认知暂不足以用在项目中,以后碰到再更新吧。因为vuex的demo我是直接将我在项目使用的东西进行改造的,所以有点乱。

 我觉得对于vuex的理解去类比一下vue更容易理解一些。

猜你喜欢

转载自blog.csdn.net/THcoding_Cat/article/details/109904782