Vuex的基本使用

  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

State

  • 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储
const store = new Vuex.Store({
  state: {conunt: 0}
})

组件访问 State 中数据的第一种方式

this.$store.state.全局数据名称

组件访问 State 中数据的第二种方式

  • 从 vuex 中按需到导入 mapState 函数
    import {mapState} from 'vuex'

  • 通过刚才导入的 mapState 函数,将当前组件需要的全局数据,映射为当前的 computed 计算属性

computed: {
  ...mapState(['count'])
}

Mutation

  • 用于变更 Store 中的数据

    • 只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据
    • 通过这种方法虽然操作起来稍微繁琐一点,但是可以集中监控所有数据的变化
  • 第二个参数是传递的参数

const store = new Vuex.Store({
  state: {conunt: 0},
  mutation: {
    add(state, step) {
      state.count += step
    }
  }
})

触发 Mutation 的第一种方式

methods: {
  add() {
    this.$store.commit('add', 5);
  }
}

触发 Mutation 的第二种方式

  • 从 vuex 中按需到导入 mapMutation 函数
    import {mapMutation} from 'vuex'

  • 通过刚才导入的 mapMutation 函数,将需要的 mapMutation 函数,映射为当前的 methods 计算属性

  • 然后再调用这个方法并且可以传递相应的参数

methods: {
  ...mapMutation(['add']),
  add() {
    this.add(5);
  }
}

Action

  • 触发 action 异步任务时携带参数
    • 再 action 中不能直接修改 state 的数据
    • 必须通过 commit() 触发某个 mutation
const store = new Vuex.Store({
  state: {conunt: 0},
  mutation: {
    add(state, step) {
      state.count += step
    }
  },
  actions: {
    addAsync({ commit }, step) {
      commit('add', step)
    }
  }
})

触发 Action 的第一种方式

methods: {
  add() {
    setTimeout(() => {
      this.$store.dispatch(addAsync, 5)
    },1000)
  }
}

触发 Action 的第二种方式

  • 从 vuex 中按需到导入 mapAction 函数
    import {mapAction} from 'vuex'

  • 通过刚才导入的 mapAction 函数,将需要的 mapAction 函数,映射为当前的 methods 计算属性

  • 然后再调用这个方法并且可以传递相应的参数

methods: {
  ...mapAction(['addAsync']),
  add() {
    setTimeout(() => {
      this.addAsync(5);
    },1000)
  }
}

Getter

  • 用于将 Store 中的数据进行加工处理形成新的数据
    • Getter 类似 Vue 的计算属性
    • Getter 的数据随着 Store 的变化而变化
const store = new Vuex.Store({
  state: {conunt: 0},
  getter: {
    showNum(state) {
      return '当前最新的数量是【"+ state.count +"】'
    }
  }
})

使用 Getter 的第一种方式

this.$store.getters.名称

使用 Getter 的第二种方式

  • 从 vuex 中按需到导入 mapGetter 函数
    import {mapGetters} from 'vuex'

  • 通过刚才导入的 mapGetter 函数,将当前组件需要的全局数据,映射为当前的 computed 计算属性

computed: {
  ...mapGetters(['showNum'])
}
posted @ 2021-03-16 14:23  懒惰ing  阅读(110)  评论(0)    收藏  举报