vuex组件传参

vuex 实现数据的全局共享,响应式更新

每一个Vuex应用的核心就是store (仓库)。"store'基本. 上就是一个容器, 它包含着你的应用中大部分的
状态(state)。Vuex 和单纯的全局对象有以下两点不同:
Vuex的状态存储是响应式的。当Vue组件从store中读取状态的时候,若store中的状态发生变化,那
么相应的组件也会相应地得到高效更新。在任意组件都可以访问 store状态中的数据

import Vuex from ' vuex'
Vue.use (Vuex)
export default new Vuex. Store({

state: {
// 定义(数据)
user: {
nane: "zeng8",
score: 280,
}
}

使用

名字:{{$store. state .user.name}}
积分: {$store.state.user .score}}


你不能直接改变store中的状态。改变store 中的状态的唯一途径就是 显式地提交(commit) mutation。

mutations: {
//改变数据的唯一方式只能在mutations 里面
//建议方法名大写,默认一个岁数是state
//第二岁数就是方法调用传入的参数
SET_ SCORE(state , data){
state.score = data;
}
},

使用

组件中访问
$store.commit("ADD_ SCORE' ,200)

这样使得我们可以方便地跟踪每-个状态的变化,从而让我们能够实现-些工具帮助我们更好地了解我们的应用。
state - data  数据

getters - computed 从现有数据中计算出新的数据

mutations 改变数据的唯一方式在mutations中

计算数据getters

例子:
getters:{
gold(state){return Math.floor(state.userInfo.score/100}
}

组件中访问
$store.getters.gold

 修改数据mutations

例子
ADD. SCORE(state,data=100){
state.userInfo.score+=data
}

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

 异步操作 Actions

例子:
setScore(context,data){
setTimeout(0=>{
context.commit("ADD_ SCORE",data);
},2000)
}

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

 模块 modules

把vuex又分成小的模块
import cart from ./modules/cart.js'
modules:{
cart
}

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

组件中访问模块的state需要带模块名称(cart)
$store.state.cart.goods


组件访问getters, actions, mutations不需 要带模块名
$store.getters.totalPrice

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

 

 

actions第一个参数context
mutations第一参数state
getters第一个参数state数据

1. context相当于组件中的$store
$store代表整个vuex,整个仓库

context.commit("mutations方法名",data)
context.dispatch("actions中的方法名",data)
context.state.数据名
context.getters.数据名

 vuex的映射方法

vuex的映射方法

  
01 导入
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'

mapState
02  mapState
在computed去计算
computed:{
//映射带模块cart
...mapState({
goods:state->state.cart.goods
)}

//不带模块
...mapState(["userInfo"])
}

03  mapState
在组件使用映射出来属性
<p>{{goods}}</p>
<p>{{userlnfo}}</p>


mapGetters 
02 mapGetters 
在computed去计算
computed:{
...mapGetters(["totalPrice"])
}

03 mapGetters 
在组件中使用
<p>总价格:{ {talPrice}}</p>

mapActions 
02 mapActions
在methods方法里面扩展
methods:{
...mapActions(["delCart"])
}

 03 mapActions
在组件中调用方法
<div @click="delCart(good.id)">

mapMutations
02 mapMutations
在methods方法里面扩展
methods:{
...mapMutations(["ADD_ SCORE"])
}


03 mapMutations
在组件中调用方法
<div @click="ADD_ SCORE(500)">

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值