、一. Vuex中的五大函数的作用
1.state:统一定义公共数据(类似于data()return)
2.muatations:使用它来修改数据
3.getters:类似于computed(计算属性,对现有的状态进行计算得到新的)
4.actions: 发起异步请求
5.modles:模块拆分
二 .在使用之前需要配置好对应的Vuex
1.第一种方式可以在创建脚手架的时候进行配置
安空格键选中Vuex
2.手动进行配置
(1)下载vuex这个包
npm i vuex
(2) 创建一个index.js文件方便模块化
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
}
})
export default store
(3)在main.js文件中导入
// 省略其他
// 1. 导入store
import store from './store'
new Vue({
// 省略其他...
store // 2. 注入Vue实例
})
三.介绍五大函数
1.state的使用
(1)在state里面定义变量
(2)使用的场景
在标签中进行使用 $store.state.class
在组件的里进行使用 this.$store.state.class
2. muatations的使用
(1)首先要明白的一点它的作用是用来更改state里面的数据
(2) 代码演示:(点击按钮使图片更改)
在data里面定义的图片
通过commit触发事件,第一个参数是函数的名字,第二个参数是新图片的地址
第一个参数是state,第二个参数是传递过来的新地址赋值给以前的地址从而更换图片
mutations: {
changeUrl(state,newlgoo){
state.logo=newlgoo
}
3. getters的使用
(1)首先来谈一下它的作用,类似于计算属性
(2)代码演示(在state里面有一个数组计算书的总价格)
gettres里面的代码:第一个参数是state
getters:{
allPrice(state){
return state.list.reduce((all,item)=>{
return all+item.price
},0)
}
在页面中的代码:通过$store.gettres.变量的名字(上方代码中的allPrice)
<h1>书的总价格是:{
{$store.getters.allPrice}}</h1>
4.actions的使用
(1)首先明白的一点是它的作用是用来发送异步的请求
(2)代码演示(发送请求拿到数据)
(3)在actions中的
getbook(context,params){
console.log(context);
axios({
method:'GET',
url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books',
}).then(res=>console.log(res))
}
解析:context是一个对象,可以通过它身上的commit方法,去触发muatations,更改数据,第二个参数是传递过来的参数。
(4)在组件中的代码
this.$store.dispatch("getbook");
解析:通过dispath来触发,后面接的是要触发的函数的名字
4.modles的使用
(1)它的作用是用来划分模块
(2)代码演示:
新创建index.js文件中
export default{
state:{
class1:'666666'
}
}
然后导入全局中进行注册
class2是要注册的名字
import class2 from '../modules/class'
modules: {
class2
}
(3)使用的方式
在页面上,在组件中需要加上this进行访问
<h2>{
{$store.state.class1.class2}}</h2>
四.辅助函数的基本使用
(1)它的作用是将公共数据变成变量来进行使用
(2)首选需要按需进行导入
import { mapState,mapMutations,mapGetters,mapActions } from 'vuex'
(3)mapState
1.在公共数据的数据中
语法:
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
2.代码演示 :
直接当成变量使用
2.在封装的模块中
(1)语法:
computed: {
...mapState('模块名', ['xxx']),
...mapState('模块名', {'新名字': 'xxx'})
}
前面增加了模块的名字
(4)mapGetters的使用
1.直接使用:this.$store.getters.xxx
2.map辅助函数:
computed:{
...mapGetters(['xxx'])
...mapGetters({新名字:'xxx'})
}
.3.在模块中进行使用
直接使用: this.$store.getters.模块名.xxx
map辅助函数:
computed:{
...mapGetters('模块名' ['xxx'])
...mapGetters( '模块名' {新名字:'xxx'})
}
(5)mapMutations的使用
1.直接使用:this.$store.commit('mutation名', 参数)
2.map辅助函数:
methods: {
...mapMutations(['mutation名']),
...mapMutations({'新名字': 'mutation名'})
}
3.在模块中进行使用
直接使用: this.$store.commit('模块名/mutation名', 参数)
methods: {
...mapMutations('模块名', ['xxx']),
...mapMutations('模块名',{'新名字': 'xxx'})
}
(6)mapActions的使用
1.直接使用:this.$store.dispatch('action名', 参数)
2.map辅助函数:
methods: {
...mapActions(['actions名']),
...mapActions({'新名字': 'actions名'})
}
3.在模块中使用
直接使用: this.$store.dispatch('模块名/action名', 参数)
map辅助函数:
methods: {
...mapActions('模块名', ['xxx']),
...mapActions('模块名',{'新名字': 'xxx'})
}
(7)注意点
在computed中: mapState,mapMutations
在methods中:mapGetters,mapActions