Vuex基础概念用法(新手入门)

一.Vuex概念及解释

定义: vue全局状态管理器。有了Vuex在任意组件/页面都可以访问vuex数据,当数据更新的时候,引用vuex的组件视图会自动更新。也就是说Vuex实现数据全局共享,响应式更新。

1.state(存放状态)

$store.store.xxx访问
提供唯一的公共数据源,所有共享的数据统一放到store的state进行储存,相似与data
例如:

state:{
    
    userlnfo:{
    
    name:"mumu",score:2500}}

组件中访问 $store.state.userlnfo.score

2.mutations(改变数据的唯一方法)

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
$store.commit(“xxx”,data)

例如:

ADD_SCORE(state,data=100Hstate.userlnfo.score+=data}

组件中访问$store.commit("ADD_SCORE",200)

3.actions(异步操作数据的方法)

Action和Mutation相似,Mutation 不能进行异步操作,若要进行异步操作,就得使用Action
$store.dispatch.(“xxx”,data)
例如:

setScore(context,data){
    
    
setTimeout((=>{
    
    
context.commit("ADD_SCORE"",data);),2000)
}

组件中访问
$store.dispatch("setScore",200)

4.getters(从现有的状态计算新的数据)

类似于vue中的computed,进行缓存,对于Store中的数据进行加工处理形成新的数据
$store.getters.xxx

例如:

getters:{
    
    
gold(state){
    
    return Math.floor(state.userlnfo.score/100)}}

组件中访问
$store.getters.gold

5.modelu(子模块)

当遇见大型项目时,数据量大,store就会显得很臃肿
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

import cart from './modules/cart.js'modules:{
    
    
cart}

//cart.js
export default{
    
    state:0,
getters:0,mutations:0,actions:(.
namespace:true,l/l开启模块的命名空间}


组件中访问模块的state需要带模块名称(cart)
$ store.state.cart.goods
组件访问getters,actions,mutations不需要带模块名$store.getters.totalPrice

开启namespace:true命名空间的模块,
getters,mutations,actions在组件中访问的时候都要带模块名this.$store.dispatch("cart/addCart",data)

二. 第一个参数注意点

  1. actions第一个参数context
    1.context相当于组件中的$store
    $store代表整个vuex,整个仓库
    context.commit("mutations方法名",data)

context.dispatch("actions中的方法名".data)

context.state.数据名
context.getters.数据名
2. mutations第一个参数state
3. getters第一个参数state数据

三.vuex的映射方法

vuex中的state与getters映射为组件的data数据(只读)
vuex中的actions和mutations映射为组件的methods方法

1.mapState

01导入
import {mapState,mapGetters,mapActions,mapMutations}from 'vuex'
02 在computed去计算

computed:{
    
    
/映射带模块cart...mapState({
    
    
goods:state=>state.cart.goods}),
//不带模块
...mapState(["userlnfo"])}

03 在组件使用映射出来属性
<p>{igoods}}</p>
<p>ffuserlnfo}}</p>

2.mapGetters

01导入
02在computed去计算
computed:{ ...mapGetters(["totalPrice"])}
03在组件中使用
<p>总价格:fftotalPrice)}</p>

3.mapActions

01导入
02在methods方法里面扩展
methods:{ ...mapActions(["delCart"])}
03在组件中调用方法
<div@click="delCart(good.id)">

4.mapMutations

01导入
02在methods方法里面扩展
methods:{ ...mapMutations(["ADD_SCORE""]))
03在组件中调用方法
<div@click="ADD_SCORE(500)">

当我们写购物车的时候通常会放在Vuex里,以下两张图可以方便大家理解购物车的逻辑。
在这里插入图片描述

在这里插入图片描述
以上就是全部内容啦,感谢观看!!!

猜你喜欢

转载自blog.csdn.net/m0_55734030/article/details/128475293