目录
Action(类似于Mutations,不同的是Action是异步)
State(用于存储状态)
1.读取状态(在store/index.js中存储count的值)
state: {
count:4
},
2.在组件中读取出来(两种方法)
直接读取
<p>{{ $store.state.count }}</p>
使用mapState读取
<template>
<div class="admin">
<p>{{ count }}</p>
</div>
</template>
<script>
import { mapState } from "vuex";
export default{
name: 'Admin',
computed:{
...mapState(['count'])
}
}
</script>
Getter(对Vuex中的数据进行过滤)
1.设置过滤条件(在store/index.js中)
state: {
count: 0
},
getters: {
getcount(state) {
return state.count > 0 ? state.count : "数据错误"
}
},
2.在组件中读取(两种方法)
直接读取
<p>{{ $store.getters.getcount }}</p>
使用mapGetters读取
<template>
<div class="plant">
<p>{{ getcount }}</p> //直接读取
</div>
</template>
<script>
import { mapGetters } from 'vuex'; 引入mapGetters
export default{
name: 'Plant',
computed:{
...mapGetters(['getcount'])
}
}
</script>
3.展示
Mutation(更改vuex中的状态)
1.改变状态的函数
mutations: {
addcount(state,num){
state.count+=num
}
},
2.在组件中设置点击事件触发函数(两种触发方法)
直接触发
this.$store.commit("addcount",10)
简洁触发
Action(类似于Mutations,不同的是Action可以是异步)
1.改变状态的异步函数
actions: {
asyncaddcount({commit}){
axios.get("http://iwenwiki.com/api/generator/list.php").then(res=>{
commit("addcount",res.data[0])
})
}
},
2.在组件里设置点击事件触发函数
3.调用函数方法
this.$store.dispatch("asyncaddcount")
简洁调用
import { mapGetters,mapActions } from 'vuex';
...mapActions(['asyncaddcount']),
this.asyncaddcount()
本文为本人自身学习记录