vuex

什么是Vuex

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

安装和引入vuex

  • 安装
yarn add vuex
  • 引入
    一般将项目应用级的状态都放到store中统一管理,项目新建一个store文件夹,这个里面存放所需的状态
//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
    state:{
        count:0
    },
    getters:{},
    mutations:{},
    actions:{}
})
export default store

定义好store后再main.js中引用

//main.js
import Vue from "vue";
import App from "./App.vue";
+ import store from "./store";
Vue.config.productionTip = false;
new Vue({
  render: (h) => h(App),
+  store,
}).$mount("#app");

核心概念

  • State

State中存储公共数据。例如组件A和组件B共同用到的数据count,在组件A中修改count的值,组件B中count会随之更改

  • 如何使用?两种方式:
  1. 在模版中使用$store.state.count
//store中定义count
const store = new Vuex.Store({
  state: {
    count: 1,
  },
  getters: {
  },
  mutations: {},
  actions: {},
});
//模版中使用$store.state.count
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ $store.state.count }}</div>
  </div>
</template>
  1. 在计算属性computed中使用
  • 在compute中定义
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ count }}</div>
  </div>
</template>
<script>
export default {
  name: "App",
  computed: {
    count(){
        return this.$store.state.count
    }
  },
};
</script>
  • 借助mapState辅助函数
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ count }}</div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "App",
  computed: {
    ...mapState(["count"]),
  },
};
</script>
  • Getters

存放从State中派生的一些状态数据,相当于State的计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

  • 如何使用?两种方式:
  1. 在模版中使用$store.getters.newCount
//store中定义
const store = new Vuex.Store({
  state: {
    count: 1,
  },
  getters: {
    newCount: (state) => {
      return state.count * 2;
    },
  },
  mutations: {},
  actions: {},
});
//模版中使用
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ $store.state.newCount}}</div>
    <div>{{ $store.getters.newCount}}</div>
  </div>
</template>
  1. 使用mapGetters辅助函数
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <!-- <div>{{ $store.state.count }}</div> -->
    <div>{{ count }}</div>
    <div>{{ newCount }}</div>
  </div>
</template>

<script>
import { mapState,mapGetters } from "vuex";
export default {
  name: "App",
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["newCount"]),
    
  },
};
</script>
  • Mutations

修改State的数据唯一方法就是commit一个mution中的方法,修改state时要调用store.commit(state,payload)提交一个payload来更改

  • 如何使用?两种方式:
  1. 调用store.commit
//store中
const store = new Vuex.Store({
  state: {
    count: 1,
  },
  getters: {
    newCount: (state) => state.count * 2,
  },
  mutations: {
    addCount(state, payload) {
      setTimeout(() => {
        payload;
        state.count++;
      },1000);
    },
  },
  actions: {},
});
//模版中
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ count }}</div>
    <div>
      <button @click="handleClick">提交</button>
    </div>
    <div>{{ newCount }}</div>
  </div>
</template>

<script>
import { mapState, mapGetters,} from "vuex";
export default {
  name: "App",
  methods: {
    handleClick() {
      this.$store.commit({
        type: "addCount",
        num: parseInt(Math.random() * 10),
      });
    },
  },
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["newCount"]),
  },
};
</script>
  1. 使用mapMutations辅助函数
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ count }}</div>
    <div>
      <button @click="addCount">提交</button>
    </div>
    <div>{{ newCount }}</div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations } from "vuex";
export default {
  name: "App",
  methods: {
    ...mapMutations(["addCount"]),
    handleClick() {
        this.addCount(Math.random() * 10)
    },
  },
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["newCount"]),
  },
};
</script>

注意:mutation必须是同步函数

  • Actions

Actions和Mutations相似,不同的是:

  1. Actions提交的是一个mutation,而不是直接改变state
  2. Actions可以提交异步操作
  • 如何使用?两种方式:
  1. 调用store.dispatch
//store中
const store = new Vuex.Store({
  state: {
    count: 1,
  },
  getters: {
    newCount: (state) => state.count * 2,
  },
  mutations: {
    addCount(state, payload) {
      state.count += payload.num;
    },
  },
  actions: {
    addCountAsync(context) {
      setTimeout(() => {
        const { commit } = context;
        commit("addCount", { num: 1 });
      });
    },
  },
});
//template中
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ count }}</div>
    <div>
      <button @click="action">action</button>
    </div>
    <div>{{ newCount }}</div>
  </div>
</template>
<script>
import { mapState, mapGetters, mapMutations } from "vuex";
export default {
  name: "App",
  methods: {
    action() {
      this.$store.dispatch("addCountAsync", { num: 1 });
    },
  },
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["newCount"]),
  },
};
</script>
  1. 使用mapActions辅助函数
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div>{{ count }}</div>
    <div>
      <button @click="action">action</button>
    </div>
    <div>{{ newCount }}</div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "App",
  methods: {
    ...mapMutations(["addCount"]),
    ...mapActions(["addCountSync"]),
    handleClick() {
      // this.addCount({ num: parseInt(Math.random() * 10) });
      this.$store.commit({
        type: "addCount",
        num: 2,
      });
    },
    action() {
      // this.$store.dispatch("addCountAsync", { num: 1 });
      this.addCountSync({ num: 1 });
    },
  },
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["newCount"]),
  },
};
</script>
  • Modules

当所有数据都放入store中,当应用变得非常复杂时,store 对象就有可能变得相当臃肿。Modules的作用就是将store划分为不同的模块,每个Modules都包含state,getters,mutations,actions。这样做方便代码维护,结构更清晰

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

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

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容

  • Vuex五个概念的简单理解。 1.State 保存共享状态信息的地方。2.Getters 类似我们单个组件中的计算...
    似朝朝我心阅读 842评论 0 6
  • Vue现代化使用方法(四)--Vuex 在组件内可以通过data属性共享数据,父子组件也可以通过props进行数据...
    去年的牛肉阅读 170评论 0 2
  • 在组件内可以通过data属性共享数据,父子组件也可以通过props进行数据共享,但如果是兄弟跨组件之间的数据共享,...
    li4065阅读 3,954评论 1 4
  • 1.什么是Vuex? 官方回答:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管...
    Angel_6c4e阅读 377评论 0 1
  • https://www.cnblogs.com/samve/p/10726629.html vue:vuex中ma...
    丁先生_b64b阅读 727评论 0 0