vuex状态管理模式学习记录

Vuex的5个状态

  • ①state: 所有的状态都存储在这里

  • ②mutations: 状态的修改都在这里

  • ③gettesr: 从state中派生数据 相当于stare中的计算属性

  • ④actions: 在这里执行异步操作

  • ⑤modules: 模块化vuex

各部分的使用方法

1. state:数据存储中心,状态中心,使用方法有两种

// 第一种 使用 this.$store.state.属性名称
// 例如:this.$store.state.属性名称
data() {
	return {
	    // this.$store.state
		user_img: this.$store.state.user.avatar,
	}
}

// 第二种 使用mapState
import { mapState } from 'vuex'
computed: {
   ...mapState({
     userInfo: 'user'
   })
   // 当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
  // ...mapState([
  //   user
  // ])
 },

2.Mutation:可以修改store数据(必须是同步函数)

const store = createStore({
  state: {
    count: 1
  },
  mutations: {
    increment (state, value) {
      // 变更状态
      state.count+=value.num
    }
  }
})
// 第一种 使用 this.$store.commit('Mutation的方法名称','参数')
this.$store.commit('increment',{
	num: 1
})

3.Action:提交的是 mutation,而不是直接变更状态(可以异步操作)

const store = createStore({
  state: {
    count: 1
  },
  mutations: {
    increment (state, value) {
      // 变更状态
      state.count+=value.num
    }
  },
  action:{
  	asynchronization(context){
  		context.commit('increment')
  	}
  }
})
// 用法 
 this.$sotre.dispatch('asynchronization')

4.Getter ,用于对Store中的数据进行加工处理形成新的数据;Store中的数据发生变化,Getter的数据也会跟着变化(store 的计算属性)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

你瞅啥灬

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

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

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

打赏作者

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

抵扣说明:

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

余额充值