vuex学习

vuex

  • 父向子传值: v-bind属性绑定
  • 子向父传值: v-on属性绑定
  • 兄弟组件之间数据共享: EventBus
    • $on 接受数据的那个组件
    • $emit 发生数据的那种组件

vuex是实现组件数据共享的机制,组件之间的数据共享

  • 便于维护和开发
  • 组件之间数据共享
  • 响应式,能够保持数据与页面的同步

访问state数据

  • 1 $store.state.count
  • 2 使用mapState


1. 导入mapState
2. 将导入的mapState,映射到当前组件的computed计算属性中

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

mutations

  • 只能mutations变更store数据,不可以直接操作。
  • 好处在于,可以监控所以的数据变化

触发mutation方式

  1. this.$store.commit()
  2. mapMutations

// 1. 定义mutation
addN (state, step) {
    state.count += step
},


// 2. 发起调用mutation
// this.$store.state.count++ // error
this.$store.commit('add')




// 另一种方式
...mapMutations(['sub', 'subN']) // 在事件中直接调用 或定义函数 this.sub()

不要在mutation中执行代码,需要使用Action进行处理异步数据。

Action

用于处理异步任务

处理ActioN - mutattion - state

  1. this.$sore.dispatch(‘addAsync’)
  2. 通过mapActions
// 在事件中调用
// dispatch函数, 专门用来触发action
this.$store.dispatch('addAsync')


// store.js
addAsync (context) {
    setTimeout(function () {
    // 在actions中, 不能直接修改state中的数据
    // 需要通过 context.commit() 处理某个mutation才可以
    context.commit('add')
    }, 1000)
},

Getter

对store已有的数据加工处理之后形成新的数据,类似VUE的计算属性。
不会修改store的数据

    使用
    // $store.getters.showNum


    // store.js
    getters: {
        showNum (state) {
        return '当前的数量是:' + state.count
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值