vuex的相关使用
mapState,mapActions,mapGetters,mapMutations
vuex中数据的调用
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { //存放状态
nickname:'zhangsan',
age:20,
gender:'男'
},
mutations: {
setAge(state, age) {
state.age = age // 修改状态
}
},
getters: {
// 类似mutations
welcome(state) {
return state.nickname + '欢迎回来'
}
},
actions: {
login({ commit }, username) {
// login默认接收第一个参数vuex实例,从中可以分离出{ commit, dispatch }可供使用
return new Promise(() => { // 模拟异步登录
setTimeout((resolve) => {
commit(username) // 得到数据后提交mutations
resolve(true)
}, 1000)
})
}
},
modules: {}, // 用于分割模块
strict: true // 严格模式,可防止用户手动修改,详细介绍见下文
})
使用
- 可以直接在vue元素上直接调用状态值
<div class="home">{{ $store.state.nickname }}</div>
- 在computed中添加返回状态值
<template>
<div class="home">
{{ nickname }}
</div>
</template>
<script>
export default {
name: 'home',
computed:{
nickname(){
return this.$store.state.nickname
}
}
}
</script>
- 更改状态值的方法
- 通过mutations调用对应方法更改状态值
// 在.vue文件中使用
this.$store.commit('setAge', 18)
// 在.js文件中使用, 首先需要引入store
import store from '@/store'
store.commit('setAge', 18)
- 遇到异步交互时更改状态值
vuex规定更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,所以还是需要调用mutations的方法,但是需要的一些异步方法不能在mutations里面进行。
vuex提供了actions供我们去对数据进行处理。
// .vue文件中调用actions方法
this.$store.dispatch('login', 'admin').then(res => {})
模块化
Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
上方代码分割成模块
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user
},
// strict: true // 严格模式,防止用户手动更改状态
strict: process.env.NODE_ENV !== 'production'
/* 但是尽量不要在生产环境下使用严格模式,严格模式会深度检测状态树来检测不合格的状态变更,在发布环境下关闭严格模式,以避免性能损失 */
})
// user.js
export default {
namespaced: true, // 设置命名空间,可便于准确定位到状态值,防止各个模块状态值的污染
state: { //存放状态
nickname:'zhangsan',
age:20,
gender:'男'
},
mutations: {
setAge(state, age) {
state.age = age // 修改状态
}
},
actions: {
login({ commit }, username) {
// login默认接收第一个参数vuex实例,从中可以分离出{ commit, dispatch }可供使用
return new Promise(() => { // 模拟异步登录
setTimeout((resolve) => {
commit(username) // 得到数据后提交mutations
resolve(true)
}, 1000)
})
}
}
}
- 当加上命名空间后,数据获取的时候就可以携带上名称,名称和
modules
中定义的名字一样,
如:
this.$store.state.user.nickname
this.$store.dispatch('user/login')
vuex中的映射方法
此处演示的例子均为
namespace:true
的情况
- 使用mapState辅助函数
import {mapState} from 'vuex'
export default {
name: 'home',
computed: {
...mapState('user', ['nickname','age','gender']) // 可直接使用
}
}
import { mapActions } from 'vuex'
methods: {
// ...mapActions('user', ['login']) //为了避免和状态值重名,也可以使用完整路径,如下
...mapActions(['user/login'])
}
// 在使用的时候
this['user/login']('admin').then(res => {})
- 使用方法类似mapState
import { mapGetters } from 'vuex'
computed: {
...mapGetters('user', ['welcome'])
}
- 和mapActions类似
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['user/login'])
}
// 在使用的时候
this['user/login']('admin').then(res => {})
各属性介绍
getters
- getters属于vuex中的计算属性,通过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页面调用的时候
computed: {
valued (){
return this.value/7
},
...mapGetters(['name', 'age']) // 可直接使用
}
Mutations
- mutations需要通过commit来调用其里面的方法,它也可以传入参数,第一个参数是state,第二个参数是载荷(payLoad),也就是额外的参数
mutations: { //类似于methods
addAge(state,payLoad){
state.age+=payLoad.number
}
}
<div class="home">
<div><button @click="test">测试</button></div>
</div>
methods:{
test(){
// 可通过前台操作触发执行mutations里面的方法
this.$store.commit('addAge',{
number:5
})
}
}
#### actions
- action中属于一部操作,mutations属于同步操作
- action不要直接取操纵state,是通过操作mutations进而去改变state里面的值
- action中的方法默认的就是异步,并且返回promise
```javascript
actions: {
getUserInfo(){
return {
nickname:'Simba',
age:20
}
}
}
// 在actions中定义一个方法:getUserInfo,并且返回一个对象
created(){
var res = this.getUserInfo()
console.log(res)
},
methods:{
...mapActions(['getUserInfo'])
}
// mapActions(['getUserInfo']) 相当于以下代码
getUserInfo(){
return this.$store.dispatch(‘getUserInfo’)
}
export default new Vuex.Store({
state: {
nickname: '',
age:0,
gender: '',
money:0
},
mutations: {
setUerInfo(state,payLoad){
state.nickname = payLoad.nickname
state.age = payLoad.age
state.gender = payLoad.gender
state.money = payLoad.money
}
},
actions: { //actions没有提供state当参数
async getToken({commit}){
var res = await axios.get('/token接口')
commit('setToken',res)
},
async getUserInfo(context){
//context可以理解为它是整个Store的对象.类似于this.$store,
他里面包含了state,getter,mutations,actions
const res = await axios.get('/接口url')
context.commit('setUerInfo',res)
//相当于 this.$store.commit,第一个参数是方法名,第二个参数是要传入的数据
context.dispatch('getToken')
//actions也可以调用自己的其他方法
},
}
})