整理vuex的基本使用

state的用法:书写和读取
Vuex书写:state: { count: 0 },
前端读取:computed: { ...mapState(['count’])}

getters的用法:书写和读取
Vuex书写:

 getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
  第二种
getters: { 
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

前端读取:

 computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
    ])
  }

mution的用法:改变state和触发方式
改变state:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})
// ...
[RECEIVE_ADDRESS] (state, {address}) {
    state.address = address
  },

在action中触发

// 异步获取食品分类列表
  async getCategorys({commit}) {
    // 发送异步ajax请求
    const result = await reqFoodCategorys()
    // 提交一个mutation
    if (result.code === 0) {
      const categorys = result.data
      commit(RECEIVE_CATEGORYS, {categorys})
    }
  },

action的用法:书写action函数,前端触发
action函数

  // 异步获取地址
  async getAddress({commit, state}) {
    // 发送异步ajax请求
    const geohash = state.latitude + ',' + state.longitude
    const result = await reqAddress(geohash)
    // 提交一个mutation
    if (result.code === 0) {
      const address = result.data
      commit(RECEIVE_ADDRESS, {address})
    }
  },

前端触发

this.$store.dispatch('incrementAsync', {
  amount: 10
})

modules中使用这些方法

import { mapState, mapActions } from "vuex";

export default {
  methods: {
    ...mapActions("moduleA", [
      "sampleFn" // -> this.sampleFn()
    ]),
    clickFn() {
      this.$store.dispatch("moduleA/sampleFn"); // 直接从store中dispatch
    }
  }
};
  // 计算属性
  computed: {
    ...mapState("addCourseware", {
      // TODO: 变量什么意思可以去vuex中add-course-ware.js文件看
      evalList: (state) => state.evalList,
    }),

    ...mapGetters("addCourseware", ["isDoneList"]),
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值