vuex的基本使用
vuex是什么?
是Vue.js 应用程序开发的 状态管理模式
vuex是项目中共享数据的管理
结构:
在根文件夹下
Vue.use(vuex)
export default new Vuex.Store({
state: {
token: ''
,
getters: {
getString(state) {
// 固定参数state
return state.token + '你好'
},
mutations: {
setToken(state, value) {
// 第一个是固定参数, 第二个是形参
state.token = value
}
},
actions: {
reflashToken(store, value) {
store.commit('setToken',实参值)
}
},
modules:{}
})
state
: 存放数据
使用:this.$store.state.属性名getters
: vuex的计算属性, 依赖state中的一个值或多个值产生一个新值, 依赖值发生变化, getters中的方法返回值也会变化
使用: this.$getters.方法名注意不用带括号
mutations
: 规定修改vuex中的数据的唯一途径
使用: this.$store.commit(‘方法名’, 实参)actions
: 用于做一些异步操作的,但是它要修改state数据还得通过mutations
使用: this.$store.dispatch(‘方法名’)
vuex中modules的使用:
作用: 将vuex的数据模块化处理
使用: 在store中新建一个modules文件夹, 创建todo.js文件
代码:
export default {
// 开启命名规范
namespaced: true,
state: {
userinfo: ''
},
getters: {},
mutations: {
getUserInfo(state, value) {
state.userinfo = value
}
},
actions: {
actionsXxx(store) {
// 在当前模块里面是不需要加todo的
store.commit('getUserInfo', 实参值)
}
}
}
//在index中导入
import todo from './modules/todo'
modules: {
todo
}
使用todo里面的数据:
state
: this.$store.state.todo.属性名getters
: this.$store.getters[‘todo/getters方法名’]
注意为什么不使用 . 语法, 因为.语法需要符合命名规范, / 不符合命名规范mutations
: this.$store.commit(‘todo/方法名’, 实参)actions
: this.$store.dispatch(‘todo/方法名’, 实参)
可以看到上面除了state中的数据是用.
之外其他的都是用/
modules下的actions
actions: {
test (store) {
console.log(store)
}
}
首先让我们看看这里面有什么吧
actions: {
test (store) {
// console.log(store)
/*
state: 访问当前模块的state数据
访问: state.属性名
rootState: 访问根模块下的state数据
rootState === this.$store.state
访问根模块下的state: rootState.属性名
访问其它模块下的state: rootState.模块名.属性名
*/
console.log(store.rootState.index)
console.log(store.rootState.test.test)
/*
getters: 用于访问当前模块的getters
访问: getters.getters方法名
rootGetters: 用于访问根模块的getters, 通过根模块能访问到所有模块的getters
访问根模块下的getters: rootGertters.根模块下的getters方法名
访问其它模块下的getters: rootGertters['模块名/其它模块下的getters方法名']
*/
console.log(store.rootGetters.index)
console.log(store.rootGetters['test/test'])
/*
commit: 用于调用mutations方法
调用本模块的mutations方法: commit('本模块的mutations方法名', 实参)
调用其它模块的mutations方法:
commit('其它模块的模块名/其它模块的mutations方法名', 实参, {root:true})
dispatch: 用于调用actions方法
调用本模块的actions方法: dispatch('本模块的actions方法名', 实参)
调用其它模块的actiosn方法
dispatch('其它模块的模块名/其它模块的actions方法名', 实参, {root:true})
*/
// 调用其它模块下mutations和dispatch方法
store.commit('test/setTest', Date.now(), { root: true })
console.log(store.dispatch('test/logTest', null, { root: true }))
}
}
稍微注意一下在todo模块中也可以调用其它组件中的mutations和actions中的方法
modules中getters的四个参数
getters: {
getLength (state, getters, rootState, rootGetters) {
平常我们只用state这一个参数就可以满足大部分需求
但是其实还有其他三个参数
getters: 用于访问当前模块下的getters
访问: getters.getters方法名
rootState: 访问根模块的state数据
访问根模块下的state: rootState.属性名
访问其它模块下的state: rootState.模块名.属性名
rootGetters: 访问根模块的getters方法, 通过根模块能访问到所有模块的getters
访问根模块下的getters: rootGetters.根模块下的getters方法名
访问其它模块下的getters: rootGetters['模块名/其它模块的getters方法名']
}
},