Vuex中mapState的用法

Vuex中mapState的用法

 

今天使用Vuex的时候遇到一个坑,也可以说是自己的无知吧,折腾了好久,终于发现自己代码的错误了。真是天雷滚滚~~~~~~

index.js

复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
import getters from './getters'

Vue.use(Vuex)

const state = {
    userInfo: { phone: 111 }, //用户信息
    orderList: [{ orderno: '1111' }], //订单列表
    orderDetail: null, //订单产品详情
    login: false, //是否登录
}

export default new Vuex.Store({
    state,
    getters,
    actions,
    mutations,
})
复制代码
复制代码
computed: {
            ...mapState([
                'orderList',
                'login'
            ]),
        },   
        mounted(){  
            console.log(typeof orderList); ==>undefind
            console.log(typeof this.orderList)==>object
        }
复制代码

mapState通过扩展运算符将store.state.orderList 映射this.orderList  这个this 很重要,这个映射直接映射到当前Vue的this对象上。

所以通过this都能将这些对象点出来,同理,mapActions, mapMutations都是一样的道理。牢记~~~

 

demo

<script>
import { mapState, mapActions } from 'vuex'
export default {
    name: 'itemcontainer',
    data() {
        return {
            itemId: null, //题目ID
            choosedNum: null, //选中答案索引
            choosedId:null //选中答案id
        }
    },
      props:['fatherComponent'],
      computed: mapState([
          'itemNum', //第几题
          'level', //第几周
          'itemDetail', //题目详情
          'timer', //计时器
    ]),
      methods: {
          ...mapActions([
              'addNum', 'initializeData',
          ]),
          //点击下一题
          nextItem(){
              if (this.choosedNum !== null) {
                  this.choosedNum = null;
                  //保存答案, 题目索引加一,跳到下一题
                  this.addNum(this.choosedId)
              }else{
                  alert('您还没有选择答案哦')
              }
          },
          //索引0-3对应答案A-B
          chooseType: type => {
              switch(type){
                  case 0: return 'A';
                  case 1: return 'B';
                  case 2: return 'C';
                  case 3: return 'D';
              }
          },
          //选中的答案信息
          choosed(type,id){
              this.choosedNum = type;
              this.choosedId = id;
          },
          //到达最后一题,交卷,请空定时器,跳转分数页面
          submitAnswer(){
              if (this.choosedNum !== null) {
                  this.addNum(this.choosedId)
                  clearInterval(this.timer)
                  this.$router.push('score')
              }else{
                  alert('您还没有选择答案哦')
              }
          },
    },
    created(){
        //初始化信息
        this.initializeData();
        document.body.style.backgroundImage = 'url(./static/img/1-1.jpg)';
    }
}
</script>

 

posted @ 2018-02-07 10:34  星期九  阅读(1133)  评论(0编辑  收藏  举报