vuex五大核心 1.State 2.Getters 3.Mutations 4.Actions 5.Module 我们项目中需要的都是:state、getters、mutations、actions里面的东西 调用方法和使用的位置也是有区别的分别是 不过vuex给我们提供了辅助函数:mapState , mapMutations , mapActions , mapGetters
调用 | 方法 | 辅助函数 |
---|---|---|
state | this.$store.state. xxx | mapState |
getters | this.$store.getters. xxx | mapGetters |
mutations | this.$store.cmmit((xxx) | mapMutations |
actions | this.$store.dispatch(xxx) | mapActions |
==注意== mapState和mapGetter的使用只能在computed计算属性中, mapMutations和mapActions使用的时候只能在methods中调用否则报错
一 、项目引入
1.安装Vuex到项目中;
npm intsall vuex --save
添加上--save是因为这个包我们在生产环境中是要使用的。
2.创建store文件夹,位置与router同一层级;
添加代码:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 创建Vuex实列
const store = new Vuex.Store({
state:{
count:1,
name:"张三",
age:20,
gender:"男"
},
getters:{// 类似vue的computed
getStateCount:function (state) { // 上面的state
return state.count+1;
}
},
mutations:{
add(state){//上面定义的state对象
state.count = state.count+1;
},
reduction(state){//上面定义的state对象
state.count = state.count-1;
}
},
actions:{// 注册action。类似vue里的methods
addFun(context){//接收一个与store实列相同的方法
context.commit("add");
},
reductionFun(context){
context.commit("reduction");
}
}
})
export default store
3.引入到main.js文件中;
import store from './store'
new Vue({
el: '#app',
store,
router,
components: { App },
template: '<App/>'
})
4.Vuex实际运用;
4.1 关于states属性引用
方式一
<h2>{{this.$store.state.count}}</h2>
方式二
<template>
<div class="home">
{{nickname}}
</div>
</template>
<script>
export default {
name: 'home',
computed:{
nickname(){
return this.$store.state.nickname
}
}
}
</script>
computed: mapState({
count: 'count'
}),
...mapState({
count: state => state.count,
name: state => state.name
})
方式三 - mapState 辅助函数
<script>
import {mapState} from 'vuex'
export default {
name: 'home',
computed: mapState(['nickname','age','gender'])
}
</script>
记住:用mapState等这种辅助函数的时候,前面的方法名和获取的属性名是一致的。
4.2 关于getters引用
getters相当于vue中的计算属性,通过getters进一步处理,得到我们想要的值,而且允许传参,第一个参数就是state.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { //存放状态
nickname:'Simba',
firstname:'张',
lastname:'三丰',
age:20,
gender:'男',
money:1000
},
getters:{
realname(state){
return state.firstname+state.lastname
},
money_us(state){
return (state.money/7).toFixed(2)
}
},
mutations: {},
actions: {},
modules: {}
})
Vue部分
方式一:
<h2>我是从Getters的计算属性的值:{{this.$store.getters.getStateCount}}</h2>
方式二:使用mapGetter
mapGetter 仅仅是将 store 中的 getter 映射到局部计算属性
computed: {
...mapGetters({
realnameALise: 'realname' // realname 不是字符串,对应的是getter里面的一个方法名字 然后将这个方法名字重新取一个别名 realnameALise
money_usALise: 'money_us' // money_us 不是字符串,对应的是getter里面的一个方法名字 然后将这个方法名字重新取一个别名 money_usALise
})
}
4.3 关于mutation引用
mutations需要通过commit来调用其里面的方法,它也可以传入参数,第一个参数是state,第二个参数是载荷(payLoad),也就是额外的参数.
(我们代码中定义的时候需要些mutations,它类似于vue中的methods.) 代码如下:
mutations: { //类似于methods
addAge(state,payLoad){
state.age+=payLoad.number
}
}
template部分
<div class="home">
<div><button @click="test">测试</button></div>
</div>
js部分
methods:{
test(){
this.$store.commit('addAge',{
number:5
})
}
}
调用的时候第二个参数最好写成对象形式,这样我们就可以传递更多信息。
但是,这样写还是会遇到同样的问题,就是如果需要操作多个数据,就会变的麻烦,这时候我们就需要mapMutations,通过它将方法映射过来
mapMutations运用
mapMutations 其实跟mapState 的作用是类似的,将组件中的 methods 映射为 store.commit 调用
methods:{
...mapMutations(['addAge'])
}
mapMutations(['addAge'])这一句就相当于下面的代码
addAge(payLoad){
this.$store.commit('addAge',payLoad)
}
参数我们可以在调用这个方法的时候写入
<button @click="addAge({number:5})">测试</button>
4.4 关于actions引用
action类似于mutation
但区别在于:action可以提交mutation
action也不要直接去操作state,而是去操作mutation
action包含异步操作,类似于axios请求,可以都放在action中写
action中的方法默认的就是异步,并且返回promise。举例代码如下:
store部分代码 - 在actions中定义一个方法:getUserInfo,并且返回一个对象
actions: {
getUserInfo(){
return {
nickname:'Simba',
age:20
}
}
}
vue部分
方法一:
created(){
var res = this.getUserInfo()
console.log(res)
},
methods:{
...mapActions(['getUserInfo'])
}
<script>
methods: {
...mapMutations({
totalAlise: 'clickTotal' // clickTotal 是mutation 里的方法,totalAlise是重新定义的一个别名方法,本组件直接调用这个方法
}),
...mapActions({
blogAdd: 'blogAdd' // 第一个blogAdd是定义的一个函数别名称,挂载在到this(vue)实例上,后面一个blogAdd 才是actions里面函数方法名称
})
} }
</script>
mapActions(['getUserInfo']) 相当于以下代码
getUserInfo(){
return this.$store.dispatch(‘getUserInfo’)
}
mapActions, action的一个辅助函数,将组件的 methods 映射为 store.dispatch 调用
方法二:
store部分:
actions: {
// 登录
Login({ commit }, userInfo) {
const username = userInfo.username.trim()
return new Promise((resolve, reject) => {
login(username, userInfo.password).then(response => {
const data = response.data
const tokenStr = data.tokenHead+data.token
setToken(tokenStr)
commit('SET_TOKEN', tokenStr)
resolve()
}).catch(error => {
reject(error)
})
})
}
}
vue部分:
methods: {
this.$store.dispatch('Login', this.loginForm).then(() => {
}).catch(() => {
})
}