Vue模块化开发
1、终端导入vuex
npm i vuex
2、创建inedx.js文件放入store目录
index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import counterOption from './counterOption.js'
Vue.use(Vuex);
export default new Vuex.Store(
{
modules:{
countHzx:counterOption
}
}
)
modules中以key-value的方式放入配置项
3、编写配置项
counterOption.js:
export default{
namespaced:true,
actions:{
add(context,value){
context.commit('add',value);
},
del(context,value){
context.commit('del',value);
},
oddAdd(context,value){
context.commit('oddAdd',value);
}
},
mutations:{
add(state,value){
state.sum += value
},
del(state,value){
state.sum -= value
},
oddAdd(state,value){
if(state.sum % 2 != 0)
state.sum += value
}
},
getters:{
bigSum(state){
return state.sum*10;
}
},
state:{
sum:0
}
}
除了最基本的配置项actions、mutations、getters、state外,新增配置项namespaced,是为了解决不同模块重名的冲突。
4、counter.vue测试
<template>
<div id="counter">
<select v-model.number="addition">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add(addition)">+</button>
<button @click="del(addition)">-</button>
<button @click="oddAdd(addition)">奇数再加</button>
<h1>结果:{{sum}}</h1>
<h1>放大十倍:{{bigSum}}</h1>
</div>
</template>
<script>
//引入对应的配置项
import {mapState,mapMutations,mapActions,mapGetters} from 'vuex'
export default{
name:'counter',
data(){
return{
addition:1,
}
},
computed:{
//使用...mapXXX(配置项名,[参数])
//参数为一个数组或单个
...mapState('countHzx',['sum']),
...mapGetters('countHzx',['bigSum'])
},
methods:{
...mapMutations('countHzx',['add','del','oddAdd']),
...mapActions('countHzx',['add','del','oddAdd'])
},
mounted(){
console.log(this);
}
}
</script>
<style scoped>
button{
margin-left: 10px;
}
</style>
重要:
mapState和mapGetters放在计算属性中
mapMutations和mapActions放在方法中