前端
引入store
//在main.js中引入store,全局组件都可以使用vuex。
import store from './store'
new Vue({
render: h => h(App),
store,
}).$mount('#app')
1. state
state是状态数据,可以通过this.$store.state来直接获取状态,也可以利用vuex提供的
mapState辅助函数将state映射到计算属性(computed)中去。
const state = {
sum:0,
realname:'张三',
age:19
}
使用方式
插值引用:{{$store.state.sum}}
使用计算属性
computed:{
// 使用计算属性表达
title( ){
return this.$store.state.title;
},
singer( ){
return this.$store.state.singer;
}
},
使用mapState辅助函数
注意:使用辅助函数的前提是要先引入
// 引入mapState,mapGetters
import {mapState,mapMutations,mapActions,mapGetters} from 'vuex';
computed:{
// 利用mapState辅助函数的简写形式,代替以上的语句,但本质也是生成计算属性
...mapState('options',['title','singer']),
},
2. mutations
更改 Vuex 的 store 中的修改状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。
// 操作state中的数据
mutations :{
editTitle(state,value){
state.title = value;
},
editSinger(state,value){
state.singer = value;
}
},
使用方式
使用methods方法,使用commit操作state中的数据
<button @click="editTitle('Lover')">更改歌名</button>
更改歌手名字
editTitle(str){
this.$store.commit('editTitle',str);
},
使用mapMutations辅助函数
// 利用mapMutation辅助函数的简写形式
...mapMutations('options',['editTitle','editSinger']),
3. actions
Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。
// 相应组件中的动作,组件中可以通过通过dispatch发送,
// actions 通过commit发送动作告知mutations
actions:{
changeSing(context,value){
setTimeout(()=>{
context.commit('editTitle',value);
},3000)
},
changeSinger(context,value){
setTimeout(()=>{
context.commit('editSinger',value);
},3000)
}
},
使用方式
使用methods方法
<button @click="changeSing('EndGame')">三秒后更改歌名</button>
三秒后更改歌名
changeSing(str){
setTimeout(()=>{
this.$store.dispatch('changeSing',str);
},3000)
},
changeSinger(str){
setTimeout(()=>{
this.$store.dispatch('changeSinger',str);
},3000)
}
使用mapActions辅助函数
// 使用mapActions辅助函数简写形式
...mapActions(['changeSing','changeSinger'])
4. getters
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数,也就是对状态在加工:
// 依赖并加工state中的数据,state中的数据也会相应改变
getters :{
otherSong(state){
return state.title = 'Delicate'
}
}
使用方式
组件中调用数据:{{$store.getters.bigNum}}
otherSong( ){
return this.$store.getters.changeOne;
}
使用mapGetters辅助函数
// 利用mapGetters辅助函数的简写形似
...mapGetters('options',['otherSong'])
示例
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const options ={
namespaced: true,
// 相应组件中的动作,组件中可以通过通过dispatch发送,
// actions 通过commit发送动作告知mutations
actions:{
changeSing(context,value){
setTimeout(()=>{
context.commit('editTitle',value);
},3000)
},
changeSinger(context,value){
setTimeout(()=>{
context.commit('editSinger',value);
},3000)
}
},
// 操作state中的数据
mutations :{
editTitle(state,value){
state.title = value;
},
editSinger(state,value){
state.singer = value;
}
},
// 管理store中的数据
state :{
title:'Daylight',
singer:'TaylorSwift'
},
// 依赖并加工state中的数据,state中的数据也会相应改变
getters :{
otherSong(state){
return state.title = 'Delicate'
}
}
}
const store = new Vuex.Store({
modules:{
options
}
})
export default store;