关于写计算属性时的mapState

1.普通的计算属性返回state中数据时,都要加this.$store.state.xxx

computed: {

  categoryList() {

    return this.$store.state.home.categoryList;

  }

}

如果有很多个计算属性的话,那么每一个都要加上this.$store.state.xxx,就会重复且繁琐

2.mapState(state的辅助函数,映射state状态树)

引进mapState后,就可以省略this.$store

//引入 mapState 
import { mapState } from "vuex";

使用:

computed: {
    ...mapState({
      //对象写法右侧需要的是一个函数,当使用这个计算属性时,右侧函数会立即执行一次
      //注入一个参数state,其实即为大仓库中的数据
    //箭头函数写法 // categoryList:(state)=>{ // return state.home.categoryList; // } categoryList(state) { return state.home.categoryList; }, }), },

 

posted on 2023-03-20 10:00  zy89898976  阅读(73)  评论(0)    收藏  举报