vuex 核心概念

快速掌握 vuex 核心概念

vuex是什么

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

官方定义:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

优点:

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

什么样的数据适合存储到 Vuex

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

安装

直接下载 / CDN 引用#

https://unpkg.com/vuex@4

Unpkg.com 提供了基于 npm 的 CDN 链接。以上的链接会一直指向 npm 上发布的最新版本。也可以通过 https://unpkg.com/vuex@4.0.0/dist/vuex.global.js 这样的方式指定特定的版本。

在 Vue 之后引入 vuex 会进行自动安装:

<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>

npm

npm install vuex@next --save

Yarn

yarn add vuex@next --save

自己构建

如果需要使用 dev 分支下的最新版本,您可以直接从 GitHub 上克隆代码并自己构建。

git clone https://github.com/vuejs/vuex.git node_modules/vuex
cd node_modules/vuex
yarn
yarn build

State

什么是state

State提供唯一的公共数据源,所有共享的数据都要统一放到 Store的 State 中进行存储。

//创建store数据源,提供唯一公共数据
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    count: 0
  }
})

访问state方式

1.通过 this.$store.state.全局数据名称 访问

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

由于在模板字符串中,是不需要写this的,所以直接写this后边的。

<h3>当前最新的count值为:{{$store.state.count}}</h3>
2.mapState 映射为计算属性

对象展开运算符(…)

mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。

通过刚オ导入的 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
	})
  },
}

Mutations

Mutations用于变更 Store中的数据。

注意:

  • 只有 mutations 里的函数,才有权利修改 state 的数据
  • mutations里不能执行异步操作
  1. 只能通过 mutations变更 Store数据,不可以直接操作 Store中的数据。
  2. 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。
const store = new Vuex.Store({
  state:{
	count:0
  },
  mutations:{
	add(state){
	  //变更状态
	  state.count++
	}
  }
})

触发 mutations的方式

1.this.$store.commit()触发 mutations
Increment() {
  this.$store.commit('add')
},

触发 mutations 时传递值

IncrementN(){
  this.$store.commit('addN',5)
}
mutations: {
  add(state) {
    // 变更状态
    state.count++
  },
  addN(state,step){
    // 变更状态
    state.count += step
  }
},
2.MapMutations 映射

从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)
  }
}

提交载荷(Payload)

你可以向 store.commit 传入额外的参数,即 mutation 的载荷(payload)

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

Actions

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

如果通过异步操作变更数据,必须通过 Action,而不能使用Mutation,但是在 Action中还是要通过触发Mutation的方式间接变更数据。

注意: 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。

触发 Actions方法

1.this.$store.dispatch 触发 Actions

store.js

// 定义 Action
const store = new Vuex.store({
  // ...省略其他代码
  mutations: {
    // 只有 mutations中的函数才有权利修改 state。
    // 不能在 mutations里执行异步操作。
    add(state) {
      state.count++
    }
  },
  actions: {
    // 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
    addAsync(context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000);
    }
  },
})

组件A

// 触发 Action
methods:{
  handle(){
    // 触发 actions 的第一种方式
    this.$store.dispatch('addAsync')
  }
}
2.mapActions 映射方法

从Vuex中按需导入 mapActions 函数。

import {mapActions} from 'vuex'

将指定的 actions 函数,映射为当前组件 methods 的方法。

methods:{
  ...mapActions(['subAsync']),
  decrementAsync(){
    this.subAsync()
  }
}

store.js

actions: {
 // 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
  subAsync(context){
    setTimeout(() => {
      context.commit('sub')
    }, 1000);
  }
}

实际的购物车示例,涉及到调用异步 API分发多重 mutation

actions: {
  checkout ({ commit, state }, products) {
    // 把当前购物车的物品备份起来
    const savedCartItems = [...state.cart.added]
    // 发出结账请求
    // 然后乐观地清空购物车
    commit(types.CHECKOUT_REQUEST)
    // 购物 API 接受一个成功回调和一个失败回调
    shop.buyProducts(
      products,
      // 成功操作
      () => commit(types.CHECKOUT_SUCCESS),
      // 失败操作
      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
    )
  }
}

Getter

  • Getter 用于对 Store中的数据进行加工处理形成新的数据。
  • Getter 不会修改 Store 中的原数据,它只起到一个包装器的作用,将Store中的数据加工后输出出来。
  • Getter可以对 Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
    Store中数据发生变化, Getter 的数据也会跟着变化。
//定义 Getter
const store = new Vuex.Store({
  state:{
	count:0
  },
  getters: {
    showNum(state) {
      return '当前最新的数量是【' + state.count + '】'
    }
  },
})

访问方式

1.通过 this.$store.getters.名称访问
this.$store.getters.名称
2.mapGetters 映射为计算属性
import { mapGetters } from 'vuex'
computed:{
	...mapGetters(['showNum'])
}

简写

其实,通过mapState,mapMutations,mapActions,mapGetters映射过来的计算属性,或者方法都可以直接调用,不用在 commit 或者 dispatch

如下:

<button @click="decrementAsync">-1Async</button>
import {mapActions} from 'vuex'

//...省略一些代码

methods: {
  ...mapActions(['subAsync']),
  decrementAsync(){
    this.subAsync()
  }
},

可以简写成:

<button @click="subAsync">-1Async</button>
import {mapActions} from 'vuex'

//...省略一些代码

methods: {
  ...mapActions(['subAsync']),
},

有参数的时候,也可以直接把参数带上,就像这样:

<button @click="subAsync(5)">+5</button>
import {mapActions} from 'vuex'

//...省略一些代码

methods: {
  ...mapActions(['addAsync']),
},
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

繁星学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值