vuex_0">vuex
-
实现组件之间数据共享的一种机制;
-
使用父子传值或兄弟传值,太麻烦了;
-
当 vuex 中的数据被修改之后,其它引用了此数据的组件,也会被同步更新;
项目中使用 Vuex
-
使用VSCode的 vue create 命令创建的 vue项目会自动配置好 vuex的各项数据
1. 运行npm install vuex 2. 在store/index.js中导入 vuex import Vuex from 'vuex' 1. 在store/index.js中安装Vuex Vue.use(Vuex) 1. 在store/index.js中创建store公共状态对象 const store = new Vuex.Store({ state: { // state 中存放的,就是全局共享的数据,可以把 state 认为 是组件中的 data count: 0 } }) 1. 在main.js中将 创建的 store 挂载到 vm 实例上 new Vue({ router, store, render: h => h(App) }).$mount('#app') 1. 如果想要在组件中访问全局的数据: this.$store.state.全局数据名称
访问store中state上的属性
-
第一种方式,官方不推荐:
- this.$store.state.数据的名称
-
第二种方式:
• 按需导入 mapState 辅助函数: //使用 结构表达式, 将vuex中获得 state对象提取出来 import { mapState } from "vuex"; • 创建一个computed属性,通过mapState,结合 ... 展开运算符,把需要的状态映射到组件的计算属性中: computed: { // 自定义的计算属性 newMsg: function() { return "----" + this.msg + "------"; }, // 通过 展开运算符,把 state中的数据映射为计算属性,这样,能够让自己的计算属性和store中的属性并存 ...mapState(["count"]) }
通过mutations方法修改 state的值
-
第一种方式:
使用this.$store.commit('方法名')来调用 mutations 中的方法 methods:{ add(){ this.$store.commit("add"); } }, ------------------------------------------- export default new Vuex.Store({ state: { //所有组件的共享数据,都存储在这个 state中 count : 100, //定义一个变量,初始值100 , 所有地方都可以引用 }, mutations: { add(state){ //state为 state区域对象,为必须参数 state.count++; }, minus(state , step){ // step为组件调用此方法时,传递的数据 state.count-= step; } }, actions: { }, modules: { } })
-
第二种方式:
• 使用mapMutaions来映射方法到methods中 import { mapMutations } from "vuex"; • 映射 mutations 方法到 methods 中 methods: { ...mapMutations(["add"]) }
修改state的其他方法,官方不推荐
-
使用$store.state.count++,修改count值
<input type="button" value="+1" @click="$store.state.count++">
actions 来提交异步的操作
-
actions如果修改 state中的数据,也需要调用 mutations中的方法进行修改。 actions类似中介, 连接mutations方法。
-
第一种使用方式
-
this.$store.dispatch(‘Action方法名称’, 参数)来访问
--- index.js: mutations: { //修改state中数据的方法, state为必须参数 add(state){ state.count++; }, minus(state , step){ state.count-= step; }, }, actions: { //actions 中提交异步方法 : context为必须的参数 ,step属于可变参数,由调用传递 addAsync(context , step){ setTimeout(() => { //延迟5秒执行 context.commit("minus" , step); }, 5000); } }, --- 组件调用: this.$store.dispatch("addAsync" , num);
-
第二种方式:官方推荐
-
使用mapActions 来映射为计算属性:
import { mapActions } from "vuex"; methods: { ...mapActions(["asyncSubtract"]) }
getters
-
getters为state数据派生后的数据。 定义的是计算属性,返回值为回调的数据
-
getters可以对 state中的数据进行 组装封装。再进行返回
-
第一种方式:通过 this.$store.getters.名称 来访问
-
第二种方式:使用mapGetters 来映射为计算属性:
----index.js getters : { //类似于计算属性, state中为定义数据, getters可以封装一个数据,加上一些其他的数据,在返回 getCount(state){ //参数state为 state区域对象,可获取定义数据d return "vuex中的count值为:"+state.count; } }, --- 组件中调用 ...mapGetters(["getCount"]) //展开解析 vuex中gettters 计算属性