1、mutations(修改状态)
(1)template中直接使用$store.commit( )触发
// template<button @click="$store.commit('ADD')">+</button>// src/vuex/store.jsconst mutations = {
// 状态变更函数
ADD (state) {
state.count++;
}}(2)利用mapMutations引入触发
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{count}}</h2>
<!-- 3、、直接调用相应的方法 -->
<button @click="ADD">+</button>
</div></template><script>// 1、引入mapMutationsimport {mapState, mapMutations} from 'vuex'export default {
data () {
return {
msg: 'Vuex test!'
}
},
// 通过mapState的JSON来赋值
computed: mapState({
count: 'count'
}),
// 2、methods中加入mapMutations
methods: mapMutations([
'ADD'
])}</script><style scoped></style>2、getters(获取state和过滤)
(1)基本用法
// src/vuex/store.jsconst getters = {
count: function(state){
// 返回加上100
return state.count + 100;
}}(2)常规获取值
computed: {
// 获取getters
count(){
return this.$store.getters.count;
}}(3)mapGetters获取值
// 1、引入mapMutationsimport {mapState, mapMutations, mapGetters} from 'vuex'// 2、使用computed: {
// 获取getters
...mapGetters(["count"])}3、actions(异步状态修改)
actions和mutations功能基本一样,不同点是,actions是异步的改变state状态,而mutations是同步改变状态。不过实际项目中一般都是通过actions改变mutations中的值。
(1)store.js中增加异步代码
// src/vuex/store.jsconst actions ={
// 触发mutations中相应的方法
add ({commit}) {
// 增加异步
setTimeout(()=>{
commit('ADD')
},3000);
console.log('我比reduce提前执行');
}}(2)常规使用
// template<button @click="add">+</button>// scriptmethods: {
add() {
//分发action
this.$store.dispatch('add');
}}(3)mapActions的使用
// template<button @click="add">+</button>// script// 引入mapActionsimport {mapState, mapActions} from 'vuex'// 使用mapActionsmethods: {
...mapActions(['add'])}转载于:https://blog.51cto.com/4547985/2390823
博客介绍了Vuex中mutations、getters和actions的使用。mutations用于同步修改状态,可在template中直接触发或用mapMutations引入触发;getters用于获取state和过滤,有多种获取值的方式;actions用于异步状态修改,实际项目常通过它改变mutations中的值。
621

被折叠的 条评论
为什么被折叠?



