store 常規(guī)使用方式
直接在 new Vuex.store 選項(xiàng)中去寫,不太好,常規(guī)方式是
創(chuàng)建文件
創(chuàng)建 client/store/state/
創(chuàng)建 client/store/state/state.js
創(chuàng)建 client/store/mutations/
創(chuàng)建 client/store/state/mutations.js
分模塊寫
// state.js 數(shù)據(jù)
export default {
count: 0
}
// mutations.js 操作
export default {
updateCount (state, num) {
state.count = num
}
}
主入口引入
// store.js
import Vuex from 'vuex'
import defaultState from './state/state'
import mutations from './mutations/mutations'
export default () => {
return new Vuex.Store({
state: defaultState, // 這里因?yàn)橛蟹?wù)端渲染,渲染時(shí),會(huì)有部分?jǐn)?shù)據(jù)傳到客戶端,這是會(huì)有覆蓋數(shù)據(jù)的操作,所以 defaultState 只是默認(rèn)狀態(tài),不是真正的狀態(tài)。
mutations // es6特性,簡(jiǎn)寫;操作都是相通的,不需要 default 標(biāo)明
})
}
getters
getters 和 組件的 computed 類似,方便直接生成一些可以直接用的數(shù)據(jù)。當(dāng)組裝的數(shù)據(jù)要在多個(gè)頁面使用時(shí),就可以使用 getters 來做。
創(chuàng)建文件夾及文件
創(chuàng)建 client/store/getters/
創(chuàng)建 client/store/state/getters.js
聲明 getters
// getters.js
export default {
fullName (state) {
return `${state.firstName} ${state.lastName}`
}
}
引入 getters
// store.js
import Vuex from 'vuex'
import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters' // 這里
export default () => {
return new Vuex.Store({
state: defaultState,
mutations,
getters // 這里
})
}
使用 getters
// app.vue
<template>
<div id="app">
<p>{{fullName}}</p>
</div>
</template>
<script>
export default {
computed: {
fullName () {
return this.$store.getters.fullName
}
}
}
</script>
簡(jiǎn)寫幫助方法
babel 默認(rèn)不支持 ... 解構(gòu)語法的,未定稿的語法
安裝 babel-preset-stage-1
npm i babel-preset-stage-1 -D
級(jí)別最高的一種。
// .babelrc
{
"presets": [
"env",
"stage-1" // 添加配置
],
"plugins": [
"transform-vue-jsx",
"syntax-dynamic-import"
]
}
mapState 簡(jiǎn)寫
// app.vue
<template>
<div id="app">
<p>{{fullName}} {{count}}</p>
</div>
</template>
<script>
import {
mapState
// mapGetters
} from 'vuex'
export default {
computed: {
...mapState(['count']), // 同名直接用數(shù)組
fullName () {
return this.$store.getters.fullName
}
}
}
</script>
不同名的話,用對(duì)象
...mapState({
counter: 'count'
}),
或者用函數(shù)
...mapState({
counter: (state) => state.count
}),
mapGetters 簡(jiǎn)寫
與 mapState 類似
...mapGetters(['fullName'])