引入Vuex
npm install --save vuex@3
使用Vuex
src下创建store文件夹,index.js文件
// 1
import Vue from 'vue'
// 2
import Vuex from 'vuex'
// 3
Vue.use(Vuex)
// 4
export default new Vuex.Store({
state:{},
mutations:{},
actions:{},
setters:{}
})
main.js中
// 1
import store from './store'
// 2
new Vue({
el:'app',
store,
})
组件中访问state中数据
-
this.$store.state.name
-
import {mapState} from 'vuex' computed:{ ...mapState(['name']) }
修改state中数据
store/index.js
mutations:{
add(state){
操作state.name
}
}
组件:
this.$store.commit('add')
mutations传参
在mutations方法中第二个参数接收传递的参数
store/index.js
mutations:{
add(state, 参数){
//
}
}
组件:
commit()中第二个参数作为传递的参数
this.$store.commit('add' , 参数)
第二种触发mutations的方法
按需导入mapMutations函数
import { mapMutations } from 'vuex'
将需要的mutations函数映射为当前组件的methods
methods:{
...mapMutations(['add','sub'],
btnHandler(){
this.add(参数)
}
}
actions
actions里用来执行异步操作
actions:{
asyncAdd(context){
setTimeout(function(){
context.commit('add')
},1000)
}
}
组件中使用dispath分发actions
this.$store.dispath('asyncAdd')
快速记忆
this.$store.state.
import { mapState, mapMutations, mapActions } from 'vuex'
...mapState([''])
...mapMustations([''])
...mapActions([''])
this.$store.commit()
this.$store.dispath()
state.name
context.commit()