vuex

103 阅读1分钟

state

所有共享的数据都要统一放到store的state中

  • 组件访问State中数据的第一种方式:
    {{ $store.state.xxx }}
    
  • 组件访问State中数据的第二种方式: import导入mapState函数,将当前组件需要的全局数据映射为当前组件的computed计算属性
    import { mapState } from 'vuex'
    
        },
        computed: {
            ...mapState(['count']),
        },
    
    {{ count }}
    

Mutation

用于变更Store中的数据

  • 只能通过mutation变更state中的数据
// 组件中
btnHandler() {
   this.$store.commit('add')
},
// store中
mutations: {
  add(state) {
   state.count++
  },
},
  • 触发mutation时传递参数
 // 组件中
 btnHandler() {
    this.$store.commit('add',3)
 },
// store中
 mutations: {
    add(state, step) {
        state.count += step
    },
},
  • 触发mutations的第二种方式
methods: {
   ...mapMutations(['sub']),
   btnHandler() {
       this.sub(3)
   },
},

// 定义
sub(state, step) {
   state.count -= step
},
  • 延时操作 不能在mutations里进行异步操作:如异步请求、定时器,会导致视图刷新但devtools里未刷新

Actions

用于处理异步任务

// 定义
mutations: {
   sub(state) {
       state.count--
   },
},
actions: {
   subAsync(context) {
       setTimeout(() => {
           context.commit('sub')
       }, 2000)
   },
},

// 使用
// 第一种触发方式
btnHandler() {
   this.$store.dispatch('subAsync')
},
  • 触发异步任务时携带参数
// 定义
mutations: {
  sub(state, step) {
      state.count -= step
  },
},
actions: {
  subAsync(context, step) {
      setTimeout(() => {
          context.commit('sub', step)
      }, 2000)
  },
},

// 使用
// 第一种触发方式
btnHandler() {
  this.$store.dispatch('subAsync', 3)
},
  • 触发actions的第二种方式
methods: {
    ...mapActions(['subAsync']),
    btnHandler() {
        this.subAsync(3)
    },
},

Getter

  • Getter用于对Store中的数据进行加工处理形成新的数据,类似计算属性
  • Store中数据发生变化,Getter的数据也会跟着变化
//定义
getters: {
    showNum(state) {
        return '当前最新的数量是: ' + state.count
    },
},
// 使用:第一种方式
this.$store.getters.showNum

// 使用:第二种方式
computed: {
    ...mapGetters(['showNum'])
},