简单使用vuex状态管理

  • 简单使用vuex状态管理已关闭评论
  • 138 次浏览
  • A+
所属分类:Web前端
摘要

概述代码示例关系图


vuex状态管理

概述

  1. vuex主要由state,mutations,actions,getters四部分构成(modules本文暂不阐述)
  2. state
    • 全局状态,只读
    • 组件读取state方式
      • 根组件上引入并挂载store对象,其他组件在计算属性通过$store获取状态
      • 可以在计算属性上使用mapState辅助函数简化state获取过程
  3. getters
    • 全局状态的计算属性
    • 组件读取getters方式,同state
    • getters参数
      • state(全局状态)
      • getters (全局其他getters)
    • 可以通过闭包(返回一个新函数)进行函数式传参调用
  4. mutations
    • 唯一改变全局状态的方法,只允许同步修改state
    • 组件使用mutations方式
      • 使用$store.commit(名字, 参数)
      • 可以在组件methods中使用mapMutations辅助函数简化
    • mutations-types(可选)
      • 可以使用常量来代替字符串,以减少提交mutation的类型的出错率
      • 如:increment -> export const INCREMENT = "increment"
  5. actions
    • 允许异步改变全局状态的方式
    • 本质是在action函数内部手动提交mutation
    • 组件使用actions方式
      • 使用$store.dispatch(名字, 参数)
    • actions参数
      • context对象,包含conmmit, dispatch方法,state等
      • payload
    • 可以在action函数中使用promise来控制异步任务顺序

代码示例

// store import Vuex from "vuex"; import Vue from "vue";  Vue.use(Vuex);  const store = new Vuex.Store({   // 开发环境下开启严格模式,不是由 mutation 函数改变的,将会抛出错误   strict: process.env.NODE_ENV !== "production",   state: {     count: 1,     msg: "我是msg",   },   mutations: {     // 同步改变count     increment(state, payload) {       state.count += payload;     },     setMsg(state, payload) {       state.msg = payload;     },   },   actions: {     // 异步改变count     incrementAsync({ commit }, payload) {       return new Promise((resolve) => {         setTimeout(() => {           commit("increment", payload);           resolve("ODK");         }, 2000);       });     },   },   getters: {     // count的计算属性,可以使用其他getters     countAddHundred({ count }, { countSubHundred }) {       return count + countSubHundred * 10 + 100;     },     countSubHundred(state) {       return state.count - 100;     },     // getters传参     countmutiNum({ count }) {       return (num) => count * num;     },   }, });  export default store;    // 组件 <template>   <div>     <input v-model="message" />     <p>{{ msg }}</p>     <button @click="btnClick">点击+10</button>     <p>{{ count }}</p>     <!-- getters传参 -->     <p>{{ countmutiNum(6) }}</p>   </div> </template>  <script> // 使用辅助函数,避免每次从$store导出 import { mapState, mapGetters, mapMutations, mapActions } from "vuex";  export default {   methods: {     ...mapMutations(["increment", "setMsg"]),     ...mapActions(["incrementAsync"]),     async btnClick() {       // 分发一个异步action,返回的是一个promise       const result = await this.incrementAsync(10);       console.log(result);     },   },   computed: {     ...mapState(["count", "msg"]),     ...mapGetters(["countAddHundred", "countSubHundred", "countmutiNum"]),     // 使用v-model双向绑定vuex的数据,需要重写set方法     message: {       get() {         return this.msg;       },       set(value) {         this.setMsg(value);       },     },   }, }; </script>   

关系图

简单使用vuex状态管理