vuex在整个vue项目中去了非常重要的作用,它管理每个vue可以随时调用和改变的数据(例如用户名或用户头像)
vuex实例里面有state,getters,mutations,action这四个对象。
创建vuex实例
新建store.js文件
引入相关的依赖并使用暴露出来
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({})
并在main.js中引入并挂在
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
state
state是存放数据的地方
export default new Vuex.Store({
state: {
test: 1
},
})
然后既可以直接在要使用的vue文件中调用。方法如下:
调用方法有两种
<!--直接调用state-->
<div>{{$store.state.test}}</div>
<!--mapState调用state-->
<div>{{test}}</div>
其中mapstate要先引入这个方法
import { mapState } from 'vuex'
并在computed中通过mapState这个方法调取state中的参数,这样调用的时候就跟调用data中的数据一样。
这里建议使用es6的扩展运算符可以放入多个state
computed: {
/*引入state*/
...mapState(['test']),
...mapState({a: 'test'})//改引用名字
},
单个引入可以直接在要用的地方
mapState([test])
这里把mutations和actions放到一起来讲。
mutations的方法需要通过commit来调用,可以传入参数,第一个为state,第二个参数为我们动态传入的参数,如果要传入多个自定义参数要使用对象的形式传入。如果mutations使用异步会报错误
mutations: { /*不可以直接调用需要通过commit来调用*/ inc: function (state,n) { console.log(n) //传入的参数 state.test = state.test + n // return new Promise(function (resolve,reject) { // if(n > 5){ // resolve(n) // }else{ // reject(n) // } // }) }, /*传入多个参数可以装在对象或数组里面*/ inc2: function (state,n) { console.log(n) //传入的参数 state.test = Number(state.test) + Number(n.a) + Number(n.b) }, }, 调用的方法有多种:
其中与mapGetters和mapState不同的是mapMtations和mapActions要在methods中引入使用
import { mapMutations, mapActions } from 'vuex'
methods: { /*mapMutations要放到methods中否则不能用*/ ...mapMutations([ 'inc', 'inc2' ]), // 引入actions ...mapActions([ 'incTest', 'incTest1' ]), }
<!--不可以直接调用mutations,需要通过commit来调用--> <button @click="$store.commit('inc2', {a: '5',b: '6'})">增加</button> <!--mapMutations调用方法--> <button @click="inc2({a: '5',b: '6'})">增加</button> <button @click="inc(10,20)">增加</button> actions调用mutations也要通过commit来调用,传入的参数第一个参数如果要传入state要以对象的形式,第二个参数是自定义的参数。如果要传入多个参数第二个参数要以对象的形式传入 /*actions可异步*/ actions: { incTest: function (actions,n) { console.log(actions,n) //第一个actions是默认必须传入的,n是要传入的参数 actions.commit('inc',n)//调用mutations的方法要用commit }, /*要传入state如下也可以像incTest然后在actions中获取*/ incTest1: function ({actions,state}, n) { state.test += n return new Promise(function (resolve,reject) { if(n > 5){ resolve(n) }else{ reject(n) } }) } }
<!--直接引用actions要用dispatch--> <button @click="$store.dispatch('incTest',10)">增加</button> <!--mapActions调用--> <button @click="incTest1(10)">增加</button>
还在持续学习中。。。