Vuex学习笔记

视频地址

一。概述

1.传统组件间传值(小范围、不频繁)

  • 父向子传值:v-bind属性绑定
  • 子向父传值:v-on事件绑定
  • 兄弟组件之间共享数据:EventBus

$on 接收数据的那个组件
$emit 发送数据的那个组件

2.vuex

vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据的共享

3.使用vuex统一管理状态的好处

  • 能够在vuex中集中管理共享的数据,易于开发和后期的维护
  • 能够高效地实现组件之间的数据共享,提高开发效率
  • 存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步

4.vuex适合存储什么样的数据

一般情况下,只有组件之间共享的数据,才有必要存储在vuex中;对于组件中的私有数据,依旧存储在组件的data中即可。

二。基本使用

  • 安装yarn add vuex
  • main.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

// 创建store对象
const store = new Vuex.Store({
  // state中存放的就是全局共享的数据
  state: {
    count: 0
  }
})

new Vue({
  render: h => h(App),
  // 将创建的共享数据对象挂载到Vue实例中
  // 所有的组件,就可以直接从store中获取全局的数据了
  store
}).$mount('#app')
  • store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

三。vuex中的核心概念

  • state
    • 提供唯一的公共数据源,所有共享的数据都要统一放到store的state中进行存储
    • 访问方式:

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

  • mutations
    • 用于变更store中的数据
    • 只能通过mutations变更store数据,不可以直接操作store中的数据;通过这种方式虽然操作起来稍微繁琐,但可以集中监控所有数据的变化
// 定义actions
export default new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
  },
  mutations: {
    // step为携带的参数
    add(state, step) {
      state.count += step
    }
  },
  actions: {
  },
  modules: {
  }
})
// 触发mutations,法一
methods: {
    btnHandle() {
      this.$store.commit('add', 3)
    }
  }
// 触发mutations,法二
import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations(['add']),
    btnHandle() {
      this.add(3)
    }
  }
}
  • 不要在mutations函数中执行异步操作
  • actions
    • 用于处理异步任务,但是在action中还是要通过触发mutation的方式间接变更数据
// 定义actions
export default new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
  },
  mutations: {
    // step为携带的参数
    add(state, step) {
      state.count += step
    }
  },
  actions: {
    addAsync(context, step) {
      setTimeout(() => {
        context.commit('add', step)
      }, 1000)
    }
  },
  modules: {
  }
})
// 触发action,法一
methods: {
    btnHandle2() {
      this.$store.dispatch('addAsync', 3)this.$store.dispatch('add', 3)
    }
}
// 触发action,法二
<button @click="subAsync">延迟1s -1</button>

import { mapActions } from 'vuex'
export default {
  methods: {
    ...mapActions(['subAsync'])
  }
}
</script>
  • getter
    • 对store中的数据进行加工处理形成新的数据(包装数据)
    • 可以对store中已有的数据进行加工处理形成新的数据,类似vue的计算属性;store中的数据发生变化,getter的数据也会跟着变化
// 定义getter
getters: {
    showNum(state) {
      return '当前最新的数量是 【' + state.count + '】'
    }
}
// 触发getter
// 法一
this.$store.getters.名称

// 法二
import { mapGetters } from 'vuex'

computed: {
    ...mapGetters(['showNum'])
  }
posted @ 2022-06-07 00:21  陆桂莺  阅读(25)  评论(0编辑  收藏  举报