state
方法一:
组件中可以使用 this.$store 获取到vuex中的store对象实例,可通过state属性属性获取count, 如下
<div> state的数据:{{ $store.state.count }}</div>
方法二:
计算属性 - 将state属性定义在计算属性中
// 把state中数据,定义在组件内的计算属性中
computed: {
count () {
return this.$store.state.count
}
}
<div> state的数据:{{ count }}</div>
方法三:
辅助函数 - mapState
mapState是辅助函数,帮助我们把store中的数据映射到 组件的计算属性中, 它属于一种方便用法
用法 : 第一步:在组件中导入mapState
import { mapState } from 'vuex'
第二步:利用延展运算符将导出的状态映射给计算属性
computed: {
...mapState(['count'])
}
第三步:使用
<div> state的数据:{{ count }}</div>
mutations
state数据的修改只能通过mutations,并且mutations必须是同步更新,目的是形成数据快照
mutations是一个对象,对象中存放修改state的方法
vuex:
mutations: {
// 方法里参数 第一个参数是当前store的state属性
// payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷
addCount (state, payload) {
state.count += payload
}
},
组件:
<template>
<div class="home">
<div> state的数据:{{ $store.state.count }}</div>
<button @click="addCount">+1</button> //每点击一次加10
</div>
</template>
<script>
export default {
methods: {
// 调用方法
addCount () {
this.$store.commit('addCount', 10) // 直接调用mutations
} // commit是提交mutations
}
}
</script>
辅助函数 - mapMutations
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['addCount'])
}
<button @click="addCount(10)">+10</button>
但是请注意: Vuex中mutations中要求不能写异步代码,如果有异步的ajax请求,应该放置在actions中
actions
state是存放数据的,mutations是同步更新数据,actions则负责进行异步操作
//vuex中:
actions: {
getAsyncCount (context) { // 第一个参数,执行的上下文对象,相当于组件中的this.$store
setTimeout(function () { // 模拟异步请求
context.commit('addCount', 123)
}, 1000)
}
}
原始调用
<button @click="addAsync">异步</button>
//不带参数
addAsync () {
this.$store.dispatch('getAsyncCount') //dispatch是调用action
}
带参数
//vuex
actions: {
getAsyncCount (context, params) { // 第一个参数,执行的上下文对象,相当于组件中的this.$store
setTimeout(function () { // 模拟异步请求
context.commit('addCount', params)
}, 1000)
}
},
//组件中
methods: {
addAsync () {
this.$store.dispatch('getAsyncCount', 111)
}
}
<button @click="addAsync">异步</button>
辅助函数 -mapActions
actions也有辅助函数,可以将action导入到组件中
import { mapActions } from 'vuex'
methods: {
...mapActions(['getAsyncCount'])
}
<button @click="getAsyncCount(111)">+异步</button>