您的位置:首页 > Web前端 > Vue.js

Vuex 单状态库 与 多模块状态库

2018-12-11 10:14 239 查看

之前对 

Vuex
 进行了简单的了解。近期在做 
Vue
 项目的同时重新学习了 
Vuex
 。本篇博文主要总结一下 
Vuex
 单状态库和多模块 
modules
 的两类使用场景。

本篇所有代码是基于 Vue-Cli 3.x 版本的脚手架工具进行编写的。

 

vuex 单状态库 Demo

这是一个仅有单个 

Vuex store
 状态库的 
Demo
。当项目中使用一个 
Vuex
 状态库就已经足够的时候,可以使用这种方式。

本 Demo 使用了一个 increment 与 decrement 的 增 / 减 事件来体现 store 数据的变化。

 

store.js

由于状态库是单一的,仅有一个 

store.js
 文件管理状态库。在该文件中一开始进行 
import
 的引入,然后使用 
Vue.use(Vuex)
 使用 
Vuex
,之后分别定义 
state
mutations
 和 
actions
,并通过 
export default new Vuex.Store({state, mutations, actions})
 模块化。

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
count: 1
}

const mutations = {
increment(state) {
state.count ++
},
decrement(state) {
state.count --
}
}

const actions = {
increment:({commit}) => {
commit('increment')
},
decrement:({commit}) => {
commit('decrement')
}
}

export default new Vuex.Store({state, mutations, actions})

 

main.js

在入口文件 

main.js
 中通过 import 引入 
store
,并注册到 
Vue
 的实例上。

import Vue from 'vue'
import App from './App.vue'
import store from './store'

// Vue-Cli 3.x
new Vue({
render: h => h(App),
router,
store
}).$mount('#app')

// Vue-Cli 2.x
// new Vue({
//   el: '#app',
//   router,
//   store,
//   components: { App },
//   template: '<App/>'
// })

 

使用 $store

在相应的组件中如下引入并在 

methods
 中使用 
mapActions

<template>
<div class="vuex">
Vuex 全局 Store count {{$store.state.count}}
<button type="button" name="button" @click="increment">加</button>
<button type="button" name="button" @click="decrement">减</button>
</div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
methods: mapActions([
'increment',
'decrement'
])
}
</script>

<style scoped>

</style>

 

Demo

关于单状态库的 

Demo
 请参考此 github
Github Demo

 

vuex 多模块状态库 Demo

当项目变得非常庞大,单个 

store
 无法满足需求的时候,可以通过多模块状态库管理多个 
store
,将各类状态分类进行维护。

本 Demo 使用了 add 与 reduce 的 增 / 减 事件来体现 store 数据的变化。

 

store

由于需要管理多个 

store
,因此在项目目录中创建 
store
 文件夹,并创建 
modules
 文件夹用来放置各个 
store
文件,并使用 
index.js
 作为入口文件。具体结构请查看 
Demo

 

main.js

同样在 

main.js
 中通过 
import
 引入 
store
,但这里是引入 
index.js
 这个入口文件。

import Vue from 'vue'
import App from './App.vue'
import store from './store/index'

 

使用 $store

除了使用方式有一定不同之外,

methods
 中的 
mapActions
 也更换了书写方式,第一个参数是对应 
store
 管理的数据,第二个参数是关于操作事件的数组。

<template lang="html">
<div class="a">
page a  {{$store.state.countA.countA}}

<button type="button" name="button" @click="add">增加</button>
<button type="button" name="button" @click="reduce">删减</button>
</div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
methods: mapActions('countA',['add','reduce'])
}
</script>

<style lang="css">
</style>

 

Demo

关于多模块状态库的 

Demo
 请参考此 github
Github Demo

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: