Vuex最全使用总结(state、mutations、actions、getters、modules模块化)

一、Vuex各部分介绍

  • 安装
npm install vuex --save

1、store中代码

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 此处存储数据
  },
  mutations: {
    // 此处用于处理state中数据,存放方法类似vue中的methods
  },
  actions: {
    // 此处用于存放异步操作
  },
  getters:{
    // 包装类,此处用于包装state中数据,类似于vue中的计算属性
  },
  modules: {
    //模块化,当数据量过大时可采用模块化
  }
})

2、main.js中代码

import store from './store'

new Vue({
  store,  //为了在 Vue 组件中访问 this.$store
  render: h => h(App)
}).$mount('#app')

二、vuex使用方法介绍

1、获取state中数据

  • 方法一:this.$store.state.全局数据名称 如:this.$store.state.count
getData() {
	  //将取得的数据给msg
      this.msg = this.$store.state.num; 
    }
  • 方法二:先按需导入mapState函数: import { mapState } from ‘vuex’
    然后数据映射为计算属性: computed:{ …mapState([‘全局数据名称’]) }
import {mapState} from 'vuex'

computed:{
    ...mapState(['num'])  //使用数时与data中数据方式相同
  }

2、使用mutations内的方法

mutations中内容
mutations: {
    add(state,step){
      //第一个形参永远都是state
      //第二个形参是调用此方法时传递的参数
      state.count+=step;
    }
  }
  • 方法一:this.$store.commit(‘mutations中被调用方法名’,被传递的参数)
<button @click="Add">+1</button>

methods:{
  Add(){
    //使用commit函数调用mutations中的对应函数,
    //第一个参数就是我们要调用的mutations中的函数名
    //第二个参数就是传递给add函数的参数
    this.$store.commit('add',10)
  }
}
  • 方法二:导入mapMutations函数import { mapMutations } from ‘vuex’,并映射到methods中,methods:{…mapMutations([‘要使用的方法名’])}
import { mapMutations } from 'vuex'

methods:{
  ...mapMutations(['add']),
    addbtn(){
      this.add(3)  //此处调用映射的add方法传递参数3
    }
}

3、使用actions内的方法

actions中内容
actions: {
  addAsync(context,step){
    setTimeout(()=>{
      context.commit('add',step);  //调用mutations中add方法
    },2000)
  }
}
  • 方法一:this.$store.dispatch(‘actions中被调用方法名’,被传递进去的参数)
<button @click="AddAsync">点击2秒后+5</button>

methods:{
  AddAsync(){
    this.$store.dispatch('addAsync',5)
  }
}
  • 方法二:导入mapActions函数import { mapActions } from ‘vuex’,并映射到methods中,methods:{…mapMutations([‘要调用的actions中的方法名’])}
import { mapActions } from 'vuex'

...mapActions(['addAsync']),
AddAsync(){
          this.addAsync(5);
      }

4、使用getters包装数据(用于对Store中的数据进行加工处理形成新的数据)

getters中内容
getters:{
    showNum(state){
      return '最新的count值为:'+state.count;  //注意最后要将包装好的数据return出去
    }
  }
  • 方法一:this. s t o r e . g e t t e r s . 包 装 数 据 名 称 如 : t h i s . store.getters.包装数据名称 如:this. store.getters.this.store.getters.showNum
{{$store.getters.showNum }}
  • 方法二:导入mapGetters 函数import { mapGetters } from ‘vuex’,并映射到computed中,computed:{…mapGetters([‘包装数据函数名’]) }
import { mapGetters } from 'vuex'
computed:{
  ...mapGetters(['showNum'])  使用数据时与data中数据方式相同,例如{{showNum}}
}

三、总结

  • state用于存储数据

  • getters用于包装数据

  • mutations用于处理state中数据,存放方法

  • actions用于进行异步操作

    上述方法二中state、getters映射至computed中,mutations、actions映射至methods中。

四、Vuex模块化示例

  • 新建moduleA.js文件内容如下,此文件用于存放Vuex模块内容。
const moduleA = {
    state: {
        count: 1
    },
    mutations: {
        add(state) {
            state.count++
        }
    },
    actions: {
        asyncAdd(context) {
            setTimeout(() => { context.commit('add') }, 2000)
        }
    },
    getters: {
        showCount(state) {
            return "moduleA中getters" + state.count
        }
    }
};

export default moduleA
  • Vuex的Store文件内容如下
import Vue from 'vue'
import Vuex from 'vuex'

// 导入Vuex的moduleA模块
import moduleA from './moduleA'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  getters: {},
  modules: {
    a: moduleA  //注册模块,命名为a
  }
})
  • Vuex模块state、getters、mutations、actions使用如下
<template>
  <div>
    <!-- 获取模块a中的state -->
    {{$store.state.a.count}}
    <!-- 使用模块a中的mutations -->
    <button @click="addCount">使用模块a中的mutations控制count加1</button>
    <!-- 使用模块a中的actions -->
    <button @click="asyncAdd">使用模块a中的actions控制count两秒后加1</button>
    <!-- 获取模块a中的getters -->
    {{$store.getters.showCount}}
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  methods: {
    addCount() {
      this.$store.commit("add");
    },
    asyncAdd() {
      this.$store.dispatch("asyncAdd");
    }
  }
};
</script>

Vuex模块化总结:在 Vuex 模块化中,state 是唯一会根据组合时模块的别名来添加层级的,后面的 getters、mutations 以及 actions 都是直接合并在 store 下。

  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VueVuexTypeScript中使用modules进行模块化的方式如下: 首先,我们需要安装好VueVuex,并使用TypeScript构建Vue项目。可以通过以下命令进行安装: ``` npm install vue vuex --save npm install typescript ts-loader --save-dev ``` 接下来,在根目录下创建`store`目录,并在该目录下创建`index.ts`文件。在`store`目录下再创建`modules`目录,并在该目录下创建对应的模块文件,例如`user.ts`和`product.ts`。 在`user.ts`模块中,定义用户相关的状态、mutations、actions和getters。例如: ```javascript // user.ts const user = { state: { userInfo: null }, mutations: { SET_USER_INFO(state, userInfo) { state.userInfo = userInfo; } }, actions: { setUserInfo({ commit }, userInfo) { commit('SET_USER_INFO', userInfo); } }, getters: { getUserInfo: state => state.userInfo } }; export default user; ``` 在`product.ts`模块中,同样定义商品相关的状态、mutations、actions和getters。 在`index.ts`文件中,引入VueVuex,并创建一个Vuex Store对象,使用`module`方法将模块添加到Store中。例如: ```javascript // index.ts import Vue from 'vue'; import Vuex from 'vuex'; import user from './modules/user'; import product from './modules/product'; Vue.use(Vuex); const store = new Vuex.Store({ modules: { user, product } }); export default store; ``` 最后,在Vue的入口文件(如`main.ts`)中,引入创建的Vuex Store,并将其挂载到Vue实例上。例如: ```javascript // main.ts import Vue from 'vue'; import App from './App.vue'; import store from './store/index'; Vue.config.productionTip = false; new Vue({ store, render: h => h(App) }).$mount('#app'); ``` 现在,我们就可以在组件中使用`this.$store`来访问Vuex的状态、提交mutations、触发actions等。在模块化的情况下,可以使用`this.$store.state.user.userInfo`来访问`user`模块中的`userInfo`状态,使用`this.$store.commit('user/SET_USER_INFO', userInfo)`来提交`user`模块中的`SET_USER_INFO`mutation使用`this.$store.dispatch('user/setUserInfo', userInfo)`来触发`user`模块中的`setUserInfo`action,以此类推。 通过以上的步骤,我们就可以在VueVuexTypeScript中使用modules进行模块化管理应用的状态。这样可以使得代码结构更清晰,易于维护和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值