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
文件,模块化能更好的进行管理