XVUE vue的好同伙

什么是vuex

  1. vuex vue项目中做数据统一管理的‘插件‘
  2. 在vuex中存储的数据,每个组件都可以引用
  3. 当vuex中的数据发生变化,引用该数据的组件会自动更新

vuex的作用,何种情况下可以使用

  1. 如果一个数据,需要在多个组件重复使用,可以把数据存放在vuex的store中
  2. 由于其更新局部会更新全局的特新,因此常用于用户数据,购物车数据

vuex的基础 你要搞懂这些单词先

单词意思
actios动作 属于异步
mutitons改变:是修改state数据的唯一方式
state状态,数据
getters获取器
moudule模块
commit提交
state

存储在 Vuex 中的数据和 Vue 实例中的 data 遵循相同的规则,例如状态对象必须是纯粹 (plain) 的

//数据,类似data
state: {
		cartNum: 10,
	},
<p>购物车总数:{{$store.state.cartNum}}</p>
mutitons和commit

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

//方法 是修改state数据的唯一方式 类似methods
mutations: {
		SET_CART_NUM(state, data) {
			state.cartNum = data;
		},
	},
<button @click="$store.commit('SET_CART_NUM',100)"></button>
<button @click="$store.commit('SET_CART_NUM',$store.state.cartNum-1)">-</button>
<button @click="$store.commit('SET_CART_NUM',$store.state.cartNum+1)">+</button>
getters
getters:{
	fee:function(state){
		return state.cartNum*0.5;
	}
}
<p>购物车总数:{{$store.getters.fee}}</p>
moudule
  1. 应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
  2. 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
actios和dispatch
  1. Action 提交的是 mutation,而不是直接变更状态
  2. Action 可以包含任意异步操作。
//定义异步 网络延迟等方法
	//即让SET_CART_NUM等延迟生效
	actions: {
		getCartNum(context,data){
			setTimeout(()=>{
				context.commit('SET_CART_NUM',data)
			},600)
		}
	},
<button @click="$store.dispatch('getCartNum',100)">延迟变</button>
<button @click="$store.dispatch('getCartNum',$store.state.cartNum-1)">延迟-</button>
<button @click="$store.dispatch('getCartNum',$store.state.cartNum+1)">延迟+</button>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值