测试员的那点事

vue-vuex-modules的使用

2020-11-26  本文已影响0人  望月成三人
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
  },
....
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:{

    }
}
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
  }
})
<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
上一篇下一篇

猜你喜欢

热点阅读