vuex

什么时候需要使用?

状态(数据)共享!

vuex工作原理

搭建vuex环境

创建文件 src/store/index.js//全局安装[--save生产环境]
npm install -g @vue/cli
//创建vue脚手架【2.6.11】我的vue是2.x版本的,如果是vue3,请下载vuex4.x的版本
vue create 项目名
//下载vuex插件
//查看npm所有版本
npm view vuex versions
//此时下载指定版本
npm i vuex@3.6.2
//index.js
//引入vue
import Vue from 'vue';
//引入vuex
import Vuex from 'vuex';
//应用vuex插件
Vue.use(Vuex);//准备actions对象-响应组件中用户的动作
const actions = {}
//准备mutations对象-修改state中的数据
const mutations = {}
//准备state对象-保存具体的数据
const state = {}//创建store
new Vuex.Store({actions,mutations,state
});
export default store;
//main.js
import Vue from 'vue'
import App from './App.vue'
import vueResouce from 'vue-resource'
import store from './store/index'Vue.config.productionTip = false
Vue.use(vueResouce);
new Vue({render: h => h(App),store: store,beforeCreate() {Vue.prototype.$bus = this}
}).$mount('#app')

⚠️ 为什么不在main.js中引入vuex?

因为使用顺序要先使用vuex,才能使用store

不管是什么顺序,import会先解析,再执行其他代码,所以不能放在main.js中

基本使用

组件读取vuex中的数据:$store.state.num

组件修改vuex中的数据:$store.dispathch('action中的方法名','数据')或 $store.commit('mutations中的方法名','数据')

若没有网络请求或者其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编号commit

求和案例

Count.vue

<template><div><h2>当前求和:{{$store.state.num}}</h2><select v-model.number="num"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="add">+</button><button @click="reduce">-</button><button @click="addOdd">当前求和为奇数再加</button><button @click="addWait">等一等在加</button></div>
</template><script>export default {name: "Count",data() {return {num: 1}},methods: {add() {// this.$store.dispatch('jia', this.num);//直接通知mutations,不需要actionsthis.$store.commit('JIA', this.num);},reduce() {// this.$store.dispatch('jian', this.num);this.$store.commit('JIAN', this.num);},addOdd() {this.$store.dispatch('jiaOdd', this.num);},addWait() {this.$store.dispatch('jiaWait', this.num);}}}
</script>

App.vue

<template><div id="app"><Count></Count></div>
</template><script>
import Count from "./components/Count";
export default {name: 'App',components: {Count}
}
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>

index.js

import Vue from "vue";
//引入vuex
import Vuex from 'vuex';
//引入vuex插件
Vue.use(Vuex);
//用于响应组件中的动作
const actions = {// jia(content, value) {//     content.commit('JIA', value);// },// jian(content, value) {//     content.commit('JIAN', value);// },jiaOdd(content, value){if (content.state.num %2 != 0){content.commit('JIA', value);}},jiaWait(content, value){setTimeout(() => {content.commit('JIA', value);},500)}
};
//用于操作数据
const mutations = {JIA(state, value) {state.num += value;},JIAN(state, value) {state.num -= value;},};
//用于存储数据
const state = {num: 0
};
//创建并暴露store(默认暴露)
export default new Vuex.Store({actions,mutations,state
})

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,beforeCreate() {Vue.prototype.$bus = this;}
}).$mount('#app')

遇到的坑!!!

vue2 => vuex3

vue3 => vuex4

如果出现Object function 报错请检查vuex版本

卸载
npm uninstall vuex
"dependencies": {"vue": "^2.6.11",
"vuex": "^3.6.2"
},
"devDependencies": {"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "~4.5.0",
}

getters

//用于对state中数据的处理
const getters = {bigSum(state) {return Math.PI * state.num;}
}
//创建并暴露store(默认暴露)
export default new Vuex.Store({actions,mutations,state,getters
})

组件中读取数据:$store.getters.bigSum

mapState,mapGetters

mapState:映射state中的数据为计算属性

mapGetters:映射getters中的数据为计算属性

computed:{//自己写计算属性author() {return this.$store.state.author;},age(){return this.$store.state.age;},bigSum(){return this.$store.getters.bigSum;},},
import {mapState,mapGetters} from 'vuex'
computed:{//结借助mapState生成计算属性,从state中读取数据。对象写法...mapState({author:'author', age:'age'}),//结借助mapState生成计算属性,从state中读取数据。数组写法...mapState(['author','age']),...mapGetters({bigSum:'bigSum'}),...mapGetters(['bigSum']),},

mapActions,mapMutations

mapActions:生成与Actions对话的方法,包含$store.dispatch(xxx)的函数

mapMutations:生成与mutations对话的方法,包含$store.commit(xxx)的函数

<button @click="add(num)">+</button>
<button @click="reduce(num)">-</button>
<button @click="addOdd(num)">当前求和为奇数再加</button>
<button @click="addWait(num)">等一等在加</button>
<!-- 需要自己传值 -->
//负责传递的是事件对象
import {mapMutations,mapActions} from 'vuex'
methods: {// add() {//     // this.$store.dispatch('jia', this.num);//     //直接通知mutations,不需要actions//     this.$store.commit('JIA', this.num);// },// reduce() {//     // this.$store.dispatch('jian', this.num);//     this.$store.commit('JIAN', this.num);// },//借助Matations生成对应的方法,方法中会调用commit去联系Mutations(对象写法)...mapMutations({add:'JIA',reduce:'JIAN'}),// addOdd() {//     this.$store.dispatch('jiaOdd', this.num);// },// addWait() {//     this.$store.dispatch('jiaWait', this.num);// }//借助mapActions生成对应的方法,方法中会调用dispatch去联系Action(对象写法)...mapActions({addOdd:'jiaOdd',addWait:'jiaWait'})}

多组件共享数据

使用mapState即可

<h3 style="color: red">人员列表组件的总人数:{{personList.length}}</h3>
computed: {...mapState(['author','age','personList']),
},
----------------------------------------------------------------------
h2 style="color: #0dff1d">求和:{{num}}</h2>
computed: {...mapState({personList: 'personList',num:'num'})
},

vuex模块化 namespace

export default {namespaced: true, //开启命令空间,可以让mapxxx识别actions: {...},mutations: {...},state: {...},getters: {...}
};
#模块化main.js
import Vue from "vue";
//引入vuex
import Vuex from 'vuex';
//引入vuex插件
Vue.use(Vuex);import countOption from "./count";
import personOption from "./person";//创建并暴露store(默认暴露)
export default new Vuex.Store({modules: {person: personOption,count: countOption}
})

#count.js
------------------------------
export default {namespaced: true,actions: {jiaOdd(content, value) {if (content.state.num % 2 != 0) {content.commit('JIA', value);}},jiaWait(content, value) {setTimeout(() => {content.commit('JIA', value);}, 500)}},mutations: {JIA(state, value) {state.num += value;},JIAN(state, value) {state.num -= value;},},state: {num: 0,author: '涂鏊飞',age: 22,},getters: {bigSum(state) {return Math.floor(Math.PI * state.num);}}
};
------------------------------
#person.js
------------------------------
import axios from 'axios';
import {nanoid} from "nanoid";export default {namespaced: true,actions: {addPersonWang(context, value) {if (value.cname.indexOf('王') !== -1) {context.commit('ADD_PERSON', value);} else {console.log('只能添加姓【王】的');}},addPersonServer(context) {axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(response => {context.commit('ADD_PERSON',{id:nanoid(),cname:response.data,clength: Math.round(Math.random(20) * 100) + "cm"})},error => {console.log(error.message)})}},mutations: {ADD_PERSON(state, value) {state.personList.unshift(value);}},state: {personList: [{id: '7aafcdf', cname: '占山', clength: '18cm'},{id: '34fergs', cname: '底层', clength: '12cm'},{id: '54vdgfd', cname: '胜多负少的', clength: '13cm'},]},getters: {showFirstPerson(state) {return state.personList[0].cname;}}
}
#Count.vue
------------------------------------------------
<template><div><code>作者:{{author}}</code><code>年龄:{{age}}</code><h2>当前求和:{{bigSum}}</h2><select v-model.number="num"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select><button @click="add(num)">+</button><button @click="reduce(num)">-</button><button @click="addOdd(num)">当前求和为奇数再加</button><button @click="addWait(num)">等一等在加</button><h3 style="color: red">人员列表组件的总人数:{{personList.length}}</h3></div>
</template><script>import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'export default {name: "Count",data() {return {num: 1}},computed:{...mapState('count',['author','age']),...mapState('person',['personList']),...mapGetters('count',{bigSum:'bigSum'}),},methods: {...mapMutations('count',{add:'JIA',reduce:'JIAN'}),...mapActions('count',{addOdd:'jiaOdd',addWait:'jiaWait'})}}
</script>
------------------------------------------------
#Perason.vue
------------------------------------------------
<template><div><h2 style="color: #0dff1d">求和:{{num}}</h2><h3>列表第一个人:{{showFirstPerson}}</h3><h2>人员列表</h2><input type="text" placeholder="输入要添加的姓名" v-model="iname"><button @click="addCname()">添加</button><button @click="addPersonWang()">添加姓王的</button><button @click="addPersonServer()">随机添加</button><ul><li v-for="p in personList" :key="p.id">【{{p.cname}}】--【{{p.clength}}】</li></ul></div>
</template><script>import {nanoid} from 'nanoid'export default {name: "Person",data() {return {iname: '',}},computed: {personList() {return this.$store.state.person.personList;},num() {return this.$store.state.count.num;},showFirstPerson() {return this.$store.getters['person/showFirstPerson'];},},methods: {addCname() {const personObj = {id: nanoid(), cname: this.iname, clength: Math.round(Math.random(20) * 100) + "cm"}this.iname = '';this.$store.commit('person/ADD_PERSON', personObj);},addPersonWang() {const personObj = {id: nanoid(), cname: this.iname, clength: Math.round(Math.random(20) * 100) + "cm"}this.iname = '';return this.$store.dispatch('person/addPersonWang', personObj);},addPersonServer() {this.$store.dispatch('person/addPersonServer');}}}
</script>
#App.vue
<template><div id="app"><Count></Count><Person></Person></div>
</template><script>
import Count from "./components/Count";
import Person from "./components/Person";
export default {name: 'App',components: {Count,Person}
}
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>

组件读取state数据

#自己读取
personList() {return this.$store.state.person.personList;
},
#mapState读取
...mapState('count',['author','age']),
...mapState('person',['personList']),

组件读取getters数据

#自己读取
showFirstPerson() {return this.$store.getters['person/showFirstPerson'];
},
#mapGetters读取
...mapGetters('count',{bigSum:'bigSum'}),

组件调用dispatch

#自己读取
-----------------------自己传参
addPersonWang() {const personObj = {id: nanoid(), cname:this.iname,clength:Math.round(Math.random(20) * 100) + "cm"}return this.$store.dispatch('person/addPersonWang', personObj);
},
-------------------------网络请求数据
addPersonServer() {this.$store.dispatch('person/addPersonServer');
}#mapActions
...mapActions('count',{addOdd:'jiaOdd',addWait:'jiaWait'})

组件调用commit

#自己调用
addCname() {const personObj = {id: nanoid(), cname: this.iname, clength:Math.round(Math.random(20) * 100) + "cm"}this.iname = '';this.$store.commit('person/ADD_PERSON', personObj);
},
#mapMutations
...mapMutations('count',{add:'JIA',reduce:'JIAN'}),

Vue教程5【vuex】getters,mapState,mapGetters,mapActions,mapMutations,模块化namespace相关推荐

  1. [vue] Vuex中四个map方法的使用 mapState mapGetters mapActions mapMutations

    1. mapState方法: 用于帮助我们映射state中的数据为计算属性 computed: {//借助mapState生成计算属性:sum.school.subject(对象写法)...mapSt ...

  2. vue教程——13 Vuex

    vue教程--13 Vuex 一 什么是Vuex? 二 vuex核心组成模块 三 vuex初体验 四 getter用法----------怎么获取state中的值呢?(B组件怎么获取并监听state的 ...

  3. vuex getters、mapGetters、...mapGetters(三)

    目录 getters 作用 getters 类似计算属性 通过属性访问 通过方法访问 mapGetters 辅助函数 getters 是将 state 中派生出的一些状态进行操作,如过滤列表中的元素, ...

  4. vuex里mapState,mapGetters使用详解

    一.引用和搭建 以下四步骤 vue项目以及vuex引用,在新版vue-cli V3 以上时,可以直接选择创建带有 vuex.详见我的另一个博客 1.初始化并创建一个项目 vue init webpac ...

  5. vuex进阶 mapState、mapGetters、mapMutations、mapActions

    一.state 1.1 引入vuex 以后,我们需要在state中定义变量,类似于vue中的data,通过state来存放状态 import Vue from 'vue' import Vuex fr ...

  6. Vuex--mapState, mapGetters, mapActions, mapMutations--使用/教程/实例

    原文网址:Vuex--mapState, mapGetters, mapActions, mapMutations--使用/教程/实例_IT利刃出鞘的博客-CSDN博客 简介 说明 本文用示例介绍Vu ...

  7. Vue状态管理vuex

    转: https://www.cnblogs.com/xiaohuochai/p/7554127.html 前面的话 由于多个状态分散的跨越在许多组件和交互间各个角落,大型应用复杂度也经常逐渐增长.为 ...

  8. VUE学习(二十一)、Vuex(getters、mapState与mapGetters、mapMutations与mapActions、多组件共享数据、模块化编码)

    VUE学习(二十一).Vuex(getters.mapState与mapGetters.mapMutations与mapActions.多组件共享数据.模块化编码) 一.Vuex普通实现求和案例 演示 ...

  9. vue——vuex mapState,mapGetters,mapMutations,mapActions

    当多次获取state中的数据时会出现大量的 $store.state.属性名 造成代码的冗余同时也很麻烦.就可使用 mapState(引用时使用的名称,'state中的属性名') 或 mapState ...

最新文章

  1. elk 的报错和优化
  2. bat批处理(二):%0 %1——给批处理脚本传递参数
  3. Android相对布局(RelativeLayout)
  4. opencv图像处理9-图像金字塔
  5. Qt中translate、tr关系 与中文问题
  6. 小程序转h5之后 vant文件查找失败:_你还在使用原生开发小程序吗
  7. php mysql随机记录_php随机取mysql记录方法小结
  8. 【TW短评测】6999元Find X2 Pro一周体验:这块120Hz屏我能玩一年
  9. php短路逻辑,JS利用短路原理简写if语句
  10. 训练的时候 nvidia:自动刷新
  11. PyCharm高校固定资产管理系统django-python+vue
  12. Android半透明对话框实现
  13. c语言函数base,c中base的用法
  14. JProfiler ERROR: Invalid license key. Aborting.
  15. php 处理eml,PHP读取、解析eml文件及生成网页详解
  16. 23岁需要做到的事情
  17. 解决win10 自动修复失败电脑无法开机问题
  18. C语言:goto循环语句
  19. 如何使用Node.js来制作电子音乐-和弦
  20. app微信登陆 小程序微信授权登陆

热门文章

  1. Windows下在Django中创建项目时ImportError: No module named django.core解决方法
  2. 一张图追踪测序的大历史背景
  3. Arabidopsis thaliana 拟南芥 长read SRX533608
  4. axure 点击按钮弹出框_Axure 教程:web网站原型设计技巧的分享
  5. JAVA基础10-继承(1)
  6. top在html5里什么意思,html中的scrolltop是什么意思
  7. js监听audio播放完毕
  8. pgadmin使用教程
  9. 三十六、请求分页管理方式
  10. Chart.js-线形图分析(参数分析+例图)