actions定义-异步修改
actions 是一种异步修改的功能
这里我们以 定时器来模拟
他的语法如下
const store = new Vuex.Store({
actions: {
函数名 (store, 可选值) {
// 异步代码, 把结果commit给mutations给state赋值
}
}
})
我们用一下就知道他的意思了
const store = new Vuex.Store({
// ...省略state和mutations此处
actions: {
asyncAddCount(store, num){
setTimeout(() => { // 1秒后, 异步提交给add的mutations
store.commit('addCount', num)
}, 1000)
},
asyncSubCount(store, num) {
setTimeout(() => { // 1秒后, 异步提交给sub的mutations
store.commit('subCount', num)
}, 1000)
}
}
})
-
actions和mutations区别?
mutations里同步修改state
actions里放入异步操作
-
actions是否能操作state?
不建议, 要commit给mutations(为调试工具可追踪)
-
actions和mutations里函数, 第一个形参分别是什么?
mutations的是state
actions的是store
他的使用方法也是两种
一种直接使用
this.$store.dispatch('actions函数名', 具体值)
第二种就是映射使用
// 1. 拿到mapActions辅助函数
import { mapActions } from 'vuex'
export default {
methods: {
// 2. 把actions里方法映射到原地
...mapActions(['actions里的函数名'])
}
}
这里我来演示一下
还是这个案例 我们给库存+ - 设置下
AddItem直接用
代码如下
<button @click="asyncAddFn">延迟1秒, 库存+1</button>
<script>
export default {
methods: {
asyncAddFn(){
this.$store.dispatch('asyncAddCount', 1)
}
}
}
</script>
SubItem映射用
<button @click="asyncSubFn">延迟1秒, 库存-1</button>
<script>
// 需求3: 映射actions到方法里
// 1. 拿到辅助函数 mapActions
// 2. 在methods内, ...mapActions(['actions函数名'])
// 3. 当普通方法使用
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions(['asyncSubCount']),
asyncSubFn(){
this.asyncSubCount(1)
}
}
}
</script>
然后给大家演示一下效果
-
actions使用方式?
方式1: this.$store.dispatch('actions方法名字', 值)
方式2: ...mapActions(['actions里的方法名']) 映射到原地使用
-
视图组件, state, mutations, actions的关系是?
getters定义-计算属性
vuex身上的全局状态-计算属性, 类似于computed
getters 依赖于 state中原始数据的变化,并返回计算后的新数据
语法如下
const store = new Vuex.Store({
getters: {
计算属性名 (state) {
return 值给计算属性
}
}
})
具体代码如下
const store = new Vuex.Store({
// ...省略其他
getters: {
allCount(state) {
return state.goodsList.reduce((sum, obj) => {
if (obj.goods_state === true) { // 选中商品才累加数量
sum += obj.goods_count;
}
return sum;
}, 0)
},
allPrice(state) {
return state.goodsList.reduce((sum, obj) => {
if (obj.goods_state) {
sum += obj.goods_count * obj.goods_price
}
return sum;
}, 0)
}
}
})
使用方法也是两种
这里我不做具体展示了
第一种 是直接使用
this.$store.getters.计算属性名
第二种 映射使用
// 1. 拿到mapGetters辅助函数
import { mapGetters } from 'vuex'
export default {
computed: {
// 2. 把getters里属性映射到原地
...mapGetters(['getters里的计算属性名'])
}
}
getters如何使用?
方式1: this.$store.getters.计算属性名
方式2: ...mapGetters(['getters里计算属性名'])