vue-vuex-modules的使用
2020-11-26 本文已影响0人
望月成三人
- 应用场景,当需要划分多模块时使用
- 创建项目选择router和vuex
-
src/route/index.js
中
import Vue from 'vue'
import VueRouter from 'vue-router'
import BuyCarView from '../views/BuyCarView.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/buy',
name:"BuyCarView",
component: BuyCarView
},
....
- 在
src/store
下新建一个buyCar.js
存放模块的内容
export default {
state:{
productNum:10
},
getters: {
desc:function(state){
return state.productNum +"件"
}
},
mutations:{
addNum:function(state){
state.productNum++
}
},
actions:{
changeNum:function(content){
setTimeout(()=>{
content.commit("addNum")
},1000)
}
},
modules:{
}
}
-
src/srore/index.js
中
import Vue from 'vue'
import Vuex from 'vuex'
import buyCar from './buyCar'
Vue.use(Vuex)
export default new Vuex.Store({
// data
state: {
},
// methods,处理state
mutations: {
},
// 异步方法,如ajax
actions: {
}
},
modules: {
// 简写buyCar
buyCar:buyCar
}
})
-
src/views/BuyCar.vue
组件中
<template>
<div class="content">
<h1>信息:buycar</h1>
<h2>产品1:{{$store.state.buyCar.productNum}}</h2>
<h2>产品2:{{buyCar.productNum}}</h2>
<h2>描述:{{desc}}</h2>
<button @click="addNum">添加数量1</button>
<button @click="changeNum">添加数量2</button>
<!-- <input type="text" :value="num" @input="addEvent" /> -->
</div>
</template>
<script>
// 导入四个map
import { mapState,mapGetters, mapActions,mapMutations} from 'vuex'
let mapStateObj = mapState(['buyCar'])
let mapGettersObj = mapGetters(['desc'])
let mapMutationsObj = mapMutations(['addNum'])
let mapActionObj = mapActions(['changeNum'])
export default {
data() {
return {}
},
mounted(){
console.log(this)
},
computed: {
// 解析state
...mapStateObj,
...mapGettersObj
},
methods: {
// 解析action和mutations的方法
...mapMutationsObj,
...mapActionObj
}
}
</script>
image.png