对于项目结构单一store的传参这里不重复讲了,可以看上一篇提到的案例。下面要讲得是项目文件结构分开的传参。
├── index.html
├── main.js
├── api
│ └── ... # 抽取出API请求
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 我们组装模块并导出 store 的地方
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
├── state.js # 根级别的 sate
└── modules
├── cart.js # 购物车模块
└── products.js # 产品模块
对于跟级别的传参:
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import * as getters from './getters'
import * as actions from './actions'
import * as mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
if (module.hot) {
module.hot.accept([
'./getters',
'./actions',
'./mutations'
], () => {
store.hotUpdate({
getters: require('./getters'),
actions: require('./actions'),
mutations: require('./mutations')
})
})
}
export default store
state.js
const state = {
DT1:0,
count: 1,
history: []
};
export default state;
getters.js
export const count = state => state.count
export const DT1 = state => state.DT1
const limit = 5
export const recentHistory = state => {
const end = state.history.length
const begin = end - limit < 0 ? 0 : end - limit
return state.history
.slice(begin, end)
.join(', ')
}
mutations.js 传参id进来
export const setId1 = (state,id) => {
state.DT1 = id
localStorage.setItem('id1', id);
}
export const increment = (state) => {
state.count++
state.history.push('increment')
}
export const decrement = (state) => {
state.count--
state.history.push('decrement')
}
actions.js 传参id进来
export const setId1 = ({ commit },id) => {
commit('setId1',id)
}
export const increment = ({ commit }) => {
commit('increment')
}
export const decrement = ({ commit }) => {
commit('decrement')
}
export const incrementIfOdd = ({ commit, state }) => {
if ((state.count + 1) % 2 === 0) {
commit('increment')
}
}
export const incrementAsync = ({ commit }) => {
setTimeout(() => {
commit('increment')
}, 1000)
}
index.vue
<template>
<div>
Value: {{ count }}
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">Increment if odd</button>
<button @click="incrementAsync">Increment async</button>
<div>
<div>Recent History (last 5 entries): {{ recentHistory }}</div>
</div>
<br>
Value: {{ DT1 }}
<button @click="setId1">=</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters(['count', 'recentHistory','DT1'])
},
/*第二种写法
computed: mapGetters([
'count',
'recentHistory'
]),*/
/* 第二种写法
methods: mapActions([
'increment',
'decrement',
'incrementIfOdd',
'incrementAsync'
]),*/
methods: {
...mapActions([
'increment',
'decrement',
'incrementIfOdd',
'incrementAsync'
]),
setId1() {
var n=this.$store.getters.count;
this.$store.dispatch("setId1",n);
}
},
}
</script>