Vuex的概述
1.1vuex是实现组件的全局状态管理的一种机制,可以方便的实现组件之间的数据共享
1.2能够在vuex中集中管理共享的数据,实现组件之间的数据共享,存储在vuex中的数据都是响应式的,保持数据与页面的同步
Vuex的基本使用
1.1安装vuex的依赖包
npm install vuex --seave
1.2导入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
1.3创建store对象
const store = new Vuex.Store({ // state中存放的就是全局共享的数据 state: {count: 0} })
1.4将store对象挂载到vue实例中
new Vue({ el: '#app', render: h => h(app), router, // 将创建的共享数据对象,挂载到Vue实例中 // 所有的组件,就可以直接从store中获取全局的数据了 store })
Vuex的核心概念:State,Mutation,Action,Getter
1.1State提供唯一的公共数据源,所有共享的数据都要统一放到 Store的 State I中进行存储。
//创建store数据源,提供唯一公共数据 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, mutations: { }, actions: { }, modules: { } })
1.1.1通过this.$stote.state全局数据名称访问
<h3>当前最新的count值为:{{$store.state.count}}</h3>
1.1.2mapState映射为计算属性
通过刚オ导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed计算属性:
<!-- 使用: -->
<h3>当前最新的count值为:{{ xCount }}</h3>
//1.导入辅助函数 mapState import { mapState } from 'vuex' export default { data() { return {} }, computed: { // mapState 可以接收数组或对象形式的参数 映射为计算属性,下面分别示例 //2.1 传入数组 ...mapState(['count']), //2.2 对象形式 可以自定义名称 ...mapState({ xCount:state => state.count }) }, }
2.Mutations变更store中的数据:Mutations用于变更 Store中的数据, 只有 mutations里的函数,才有权利修改 state 的数据, mutations里不能包含异步操作。
const store = new Vuex.Store({ state:{ count:0 }, mutations:{ add(state){ //变更状态 state.count++ } } })
2.1.1通过this.$stote.commit()触发mutataions(第一种方式)
Increment() { this.$store.commit('add') },
2.2.1触发mutation时传递参数
IncrementN(){ this.$store.commit('addN',5) } mutations: { add(state) { // 变更状态 state.count++ }, addN(state,step){ // 变更状态 state.count += step } },
2.3.1MapMutationos映射方法
从vuex中按需导入 mapMutations函数
import {mapMutations} from 'vuex'
通过刚才按需导入的 mapMutations函数,映射为当前组件的methods函数
// store mutations: { add(state) { // 变更状态 state.count++ }, sub(state) { state.count-- }, addN(state, step) { // 变更状态 state.count += step }, subN(state, step) { state.count -= step } }, // 组件A import { mapState,mapMutations } from 'vuex' methods:{ ...mapMutations(['sub','subN']), decrement(){ // 调用 this.sub() }, decrementN(){ this.subN(5) } }
3.1Action用于处理异步任务,如果通过异步操作变更数据,必须通过Action,而不能直接使用mutation,但是在action中还是要通过触发mutation的方式间接变更数据
3.1.1this.$store.dispath()触发actions
// 定义mutation mutations: { // 第一个形参永远是自身的state,state代表的是全局数据对象 add(state) { state.count++ } }, actions: { addAsync(context) { // 在actions中不能直接修改,state中的数据,必须通过context.commit()触发某个mutation才行 setTimeout(() => { context.commit('add') }, 1000) } },
方法调用
btnHandler3() { this.$store.dispatch('addAsync') }
4.Getter
4.1.1用于对Store中的数据进行加工处理形成新的数据,类似于vue中的计算属性
4.1.2Store中的数据发生变化,Getter的数据也会跟着变化
基于Vuedx的案例
浙公网安备 33010602011771号