Vuex是一个专为 Vue.js 应用程序开发的状态管理模式,其store管理多个组件共享状态
一、安装
npm install vuex --save
二、使用
在项目src下新建store文件夹,然后创建index.js,import所需的模块,Vue.use()使用插件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
实例化Vuex中的Store对象
const store = new Vuex.Store({
state: { //类似 vue实例对象 的 data
name:"张三"
},
mutactions: { //类似 vue实例对象 的 methods
getname(state[,params]) { //后面可接收传过来的参数
console.log(state.name) //输出'张三'
}
},
getters: { //类似 vue实例对象 的 computed
name11(state) {
return state.name + '11'
},
fullname(state,getters) { //不接受传参,若要传参请使用callback
return getters.name11 + 'fullname' //getters.name11返回的数据进行加工
}
},
actions: { //存放执行异步操作的函数
getdata(context[,params]) { //context 即 store对象 ,可传参
settimeout(()=>{ //异步操作
context.commit('getname') //调用管理的mutactions函数
},1000)
}
},
modules: { //将管理的状态模块化
moduleA: {
state: {},
mutactions: {
},
getters: {
foo(state,getters,rootState,rootGetters) {
}
},
...//与store结构相同
}
}
})
最后,向外暴露store对象
export default store
在主文件main.js中的vue实例上进行挂载,挂载后在.vue文件中通过使用this.$store来获取vuex实例对象store
//main.js
import Vue from 'vue'
import App from './App'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
调用store的资源
- 调用
store中mutactions的函数,需要使用this.$store.commit('函数名'[,参数])或者this.$store.commit({type:'函数名',key:value})(后者的方式mutactions中函数的第二参数是payload对象) - 调用
store中actions的函数,需要使用this.$store.dispatch('函数名') - 调用
store中modules的状态(state数据),需要使用this.$store.模块名来获取module中state对象 - 调用
store中modules的函数与普通调用函数的方法一样
注:模块中函数名和store的函数名最好不要一样,如果同名会调用store的函数
部分抽离
-
store中的actions、getters、mutactions可以直接在store文件夹下创建对应的.js文件并暴露 -
modules可以创建modules文件夹,再创建对应的.js文件,模块化能更好的进行管理