有的朋友会疑惑vue-element-admin中vuex是怎么使用的,首先要说的是,vue-element-admin中把store给model化了,就是说分成a/b/c/d...的很多模块,每个模块都有自己的state/mutation/getter/action,在大的项目中,这么做的效果还是显而易见的,因为单一的状态树种,随着项目的不断迭代,会有很多状态和mutation放入同一个state/mutation对象中,难免会使对象臃肿不堪,而且模块化也是大家所追求的嘛!
ok废话不多说,直接撸实操
一:首先要创建一个自己的store模块,在store/modules中创建一个my.js,并在其中书写自己的state/mutation/action
const my = {
state: {
ceshi: 1
},
mutations: {
CESHI_NUM: (state, data) => {
state.ceshi += data
},
},
actions: {
ceshi({ commit, state }, data) {
commit('CESHI_NUM', data)
},
}
}
export default my
二:在store的index中注册my.js
import my from './modules/my'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
my
}
})
三:在组件中调用和改变状态树
<template>
<div class="">
<el-button type="primary" icon="el-icon-search" @click="change_vuex">测试vuex</el-button>
<el-button type="primary" icon="el-icon-search" @click="change_vuex_ansnc">异步测试vuex</el-button>
<div>原stor中注册的为:{{ ceshia }}</div>
</div>
</template>
<script>
import store from '../../../store'
export default {
mounted() {
},
data() {
return {
}
},
computed: {
ceshia() {
return store.state.my.ceshi
}
},
methods: {
change_vuex() {
store.commit('CESHI_NUM',10)
},
change_vuex_ansnc() {
store.dispatch('ceshi', 10)
},
}
}
</script>
ok,过程是不是很简单!
本文介绍了vue-element-admin中vuex的使用。vue-element-admin将store模块化,避免单一状态树随项目迭代变得臃肿。还给出实操步骤:先在store/modules创建my.js并写state等,再在store的index中注册,最后在组件中调用和改变状态树。
1017





