Vuex的属性及基本用法

1.state:提供唯一的公共数据源,所有共享的数据统一放到Store的state中进行存储

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

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

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

// 1.从vuex中按需导入mapState函数
import { mapState } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapState(['全局数据名称'])
}

2.mutation:用于变更Store中的数据

①只能通过mutation变更Store数据,不可以直接操作Store中的数据

②通过这种方式虽然操作起来稍微繁琐,但是可以集中监控所有数据的变化

③可以在触发mutations时传递参数 第二个参数

// 定义 mutation 
const store = new Vuex.store({
  state: {
    count: 1
  },
  mutations: {
    add(state) {    //  add(state, step)
      //变更状态
      state.count++   // state.count += step
    }
  }
})
//触发mutation 
methods: {
  handel() {
     this.$store.commit('add')  // this.$store.commit('add', 4)
  }
}

触发mutations的第一种方法:

this.$store.commit()

触发mutations的第二种方法:

// 1.从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapMutations(['方法名'])
}

3.action:用来处理异步任务

在Aciton中通过触发Mutation的方法间接变更数据

用法:

// 定义 mutation 
const store = new Vuex.store({
  state: {
    count: 1
  },
  mutations: {
    add(state) {    //  add(state, step)
      //变更状态
      state.count++   // state.count += step
    }
  },
  actions: {
    addAsync(context) {   // addAsync(context, step)
      setTimeout(() => {
        context.commit('add')  // context.commit('add', 3)
      }, 1000)
    }
  }
})
//触发mutation 
methods: {
  handel() {
     this.$store.dispatch('add')  // this.$store.dispatch('add', 4)
  }
}

触发actions的第一种方法:

this.$store.dispatch()

触发actions的第二种方法:

// 1.从vuex中按需导入mapActions函数
import { mapActions } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapActions(['方法名'])
}

4.getter:用于对store中的数据进行加工处理形成新的数据

①getter 可以对store中已有的数据加工处理形成新的数据

②store中数据发生变化,getter的数据也会跟着变化

// 定义 mutation 
const store = new Vuex.store({
  state: {
    count: 1
  },
  getters: {
   showNum(state) {
     return '当前最新的数据是:'+state.count
   }
  }
})

触发getters的第一种方法:

this.$store.getters.方法

触发actions的第二种方法:

// 1.从vuex中按需导入mapGetters函数
import { mapGetter } from 'vuex'
// 2.将全局数据,映射为当前组件的计算属性
computed: {
   ...mapGetter(['方法名'])
}

5.module:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值