试想一个电商网站,页面繁多,资料的部分前台会有购物车、商品、评价、促销活动,後台部分有订单、折扣码、帐务等等等…众多的资料如果都放在同一支 store
,要不要个一千行?
为了防止这样的情况,我们可以将我们的资料们依据自己的分类拆分成一个个模组,以便後续的管理维护。
新增模组其实很~~简单,比如说我想要新增一支专门用来管理次数的模组,以此为范例
store
资料夹新增一支 count.js
,里面长这样:export default {
state: {
count: 0
},
mutations: {
ADD_COUNT (state) {
state.count += 1
}
},
actions: {
updateCount (context, status) {
context.commit('ADD_COUNT', status)
}
}
}
我简单说明以上内容
state
资料里面存 count
次数mutations
放更新 count
的方法actions
呼叫 mutations
的方法以更新 count
store
绑定store/index.js
一声对吧!import countModules from './count'
export default new Vuex.Store({
modules: {
countModules
}
})
只要将我们的 count
模组 import
进来,并在 modules
新增即可唷!
<template>
<div id="app">
<div>
<button @click="updateCount">addCount</button><span>{{ count }}</span>
</div>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
updateCount () {
this.$store.dispatch('updateCount')
}
},
computed: {
count () {
return this.$store.state.countModules.count
}
}
}
</script>
我们在 methods
使用到了 count
模组的 action
,使用方式不变,一样用 dispatch
去呼叫即可。
但在 computed
中为了取得 count
的值,我们不是直接用 this.$store.state.count
,而是变成 this.$store.state.countModulest
,这是为什麽呢?
因为有一个需要特别注意的地方!!!
在模组中,state预设为模组区域变数,而actions/mutations/getters预设为全域变数
所以我们要取得的不是 store.state
资料,而是他旗下模组 countModules
的资料,故而是使用this.$store.state.countModulest
唷!
今天我们创建了我们第一个 vuex
模组,给自己掌声鼓励鼓励!
明天我们在一起研究,关於模组中一些细节运用的方式吧!
<<: Day9 You have to trust that the dots will somehow connect in your future
GitHub:https://github.com/dannypc1628/Angular-Tou...
[Day23] Sticky Nav 需要用到的技巧与练习目标 offsetHeight offse...
本篇文章同步发表在 HKT 线上教室 部落格,线上影音教学课程已上架至 Udemy 和 Youtu...
前言 前面用棋盘方格为例,练习了如何用 grid-template-areas、 grid-colu...
开始建立专案 ...