Vuex学习

1、组件之间共享数据的方式:

父-子:v-bind属性绑定
子-父:v-on事件绑定
兄弟组件之间共享数据:EventBus
on接收数据组件emit发送数据的组件

2、Vuex是用来管理全局数据。实现组件数据共享。

3、基本使用:

store.js文件:
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {

  },
  mutations: {

  },
  actions: {

  }
})

main.js文件挂载:
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

4、Vuex核心概念:

state:提供唯一公共数据源;

取值:this.$store.state.属性名
导入mapState函数,将全局数据映射为计算属性即可。

import { mapState } from 'vuex'

export default {
  name: 'vuexDemo',
  computed: {
    ...mapState(['count'])
  }
}

<template>
  <div>
    <h3>当前最新的count值为:{{ count }}</h3>
    <button>-</button>
  </div>
</template>
mutation用于变更Store中的数据,不可以直接操作store中的数据。
export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add(state) {
      state.count++
    }
  },
  actions: {

  }
})

btnHandle() {
  this.$store.commit('add')
}

mutations传递参数:

addN(state, step) {
  state.count += step
}

this.$store.commit('addN', 3)
import { mapState, mapMutations } from 'vuex'

methods: {
    ...mapMutations(['sub']),
    btnHandle1() {
      this.sub()
    }
}

不要在mutions函数中,执行异步操作。

Action用于处理异步任务。
actions: {
    addSync(context) {
      // 在actions中不能修改state中的数据
      // 必须通过context.commit()触发某个mutation才行
      setTimeout(() => {
        context.commit('add')
      }, 1000);
    }
  }
btnHandle1() {
  this.$store.dispatch('addSync')
}

触发actions异步任务携带参数。

...mapActions(['addSync']),
btnHandle2() {
  this.addSync()
}
Getter:
getters: {
    showNum(state) {
      return '当前最新的数据是[' + state.count + ']'
    }
  }

this.$store.getters.名称

import {mapGetters } from 'vuex'
...mapGetters(['showNum']),

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 包含如何新建项目和上传github,包含vuex的State、Getters、Mutations、Actions、...
    锋叔阅读 2,994评论 9 39
  • Vuex学习 一、Vuex是做什么的? 官方解释:Vuex是一个专为Vue.js应用程序开发的状态管理模式,它采用...
    waigo阅读 333评论 0 0
  • 上次学习了vue-router的使用,让我能够在各个页面间切换,将页面搭建了起来。这次则要学习vue的状态管理模式...
    VioletJack阅读 29,151评论 3 46
  • 官方文档 1、思想:基于响应式的原理:所有的状态的变更都是因为数据的变化引起的。 2、背景:在传统的vue应用中,...
    美乃滋酱啊阅读 2,097评论 0 5
  • 什么是Vuex? 引用官方加以我自己的理解: Vuex 是一个专门为 Vue.js 应用程序开发的状态管理器. 它...
    人话博客阅读 925评论 0 49

友情链接更多精彩内容