简单的vuex使用
Vuex是一个专门为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,解决多组件数据通信问题
配置vuex
1, 安装vuex, vue2版本对应的事vuex3
npm i vuex@3
2, 配置vuex, 在src文件夹下建立store文件夹并建立index.js
import Vue from 'vue'
import Vuex from 'vuex'
import test from './modus/test.js'
Vue.use(Vuex)
export default new Vuex.Store({
namespaced: true, // 作用是隔离模块的状态管理,避免命名冲突,并提高代码的可维护性和可读性
modules: {
// 引入的模块js, 也可以将所有数据写到index.js里, 建议按模块建立文件
test
}
})
在main.js里引入vux
import store from '@/store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
基本方法
在store文件夹下建立modus文件夹并建立test.js文件
state属性:基本数据;
getters属性:从 state 中派生出的数据;
mutation属性:更新 store 中数据的唯一途径,其接收一个以 state 为第一参数的回调函数;
action 属性:提交 mutation 以更改 state,其中可以包含异步操作;
module 属性:用于将 store分割成不同的模块。
1, state
包含了store中存储的各个数据, 使用方法:
export default {
state: {
name: '曹操',
}
}
如果在vue文件里想要给name赋值或者取值方法如下:
// 取值
let storeName = this.$store.state.test.name;
// 赋值
this.$store.state.test.name = '曹丕'
2, mutations
export default {
state: {
name: '曹操',
},
mutations: {
// 更新name
setName(state, payload){
state.name = payload.name;
}
}
}
在vue文件里调用mutations里的方法,使用commit
let params = {
name: '曹丕'
}
this.$store.state.commit('setName', params)
3, actions 获取异步数据并给state的字段复制
export default {
state: {
name: '曹操',
},
mutations: {
// 更新name
setName(state, payload){
state.name = payload.name;
}
},
actions: {
getName({commit}, params){
http.get('/getName',{
params
}).then(res => {
commit('setName', res);
})
}
}
}
在vue文件里调用actions里的方法使用dispatch
let params = {} // 参数
this.$store.dispatch('getName', params)