【Vue学习笔记】—— vuex的语法 { }

学习笔记

  • 作者:o_Ming

    • vuex

Vuex

++ state ++ (用于存储全局数据)

  • 组件访问 state 中的全局数据的方式1
this.$store.state.全局数据
  • 组件访问 state 中的全局数据的方式2
// 组件中按需导入 mapState 函数
import { mapState } from 'vuex'
export default {
	name: 'app',
	computed: {
		// 将全局数据 映射 为计算属性
		...mapState(['inputValue'])
	},
}
<p>{{ inputValue }}</p>

++ mutations ++ (用于变更store存储的数据,不要在mutations中进行异步操作)

  • 调用mutations的方式1
// 在store中定义
mutations: {
	add(state,param1){
		state.count = param1
	}
}
// 在组件中调用
this.$store.commit('add',param1)
  • 调用mutations的方式2
import { mapMutations } from 'vuex'
// 将指定的mutations函数,映射为组件的methods函数
export default{
	methods: {
		...mapMutations(['add']),
		fun(){
			this.add()
		}
	}
}

++ getters ++ (用于对Store中的数据加工处理形成新的数据)

  • 定义 getters
getters: {
	showNum: state => {
		return '当前最新的数据是: ' + state.count
	}
}
  • 使用 getters
    • 方式1this.$store.getters.名称

    • 方式2

import { mapGetters } from 'vuex'
export default {
	name: 'app',
	computed: {
		...mapGetters(['showNum'])
	}
}
<p>{{ showNum }}</p>
  • getterscomputed (都可以缓存计算结果)
getters: {
	format(state){
		console.log("getters format 执行")
		return state.txt + " Vuex"
	}
}
<!-- "getters format 执行" 这句话只会执行一次 -->
<h1>{{ this.$store.getters.format }}</h1>
<h1>{{ this.$store.getters.format }}</h1>
<h1>{{ this.$store.getters.format }}</h1>
<h1>{{ this.$store.getters.format }}</h1>
<h1>{{ this.$store.getters.format }}</h1>
computed: {
	format(){
		console.log("computed format 执行")
		return this.msg + " yeap!"
	}
}
<!-- "computed format 执行" 这句话只会执行一次 -->
<h1>{{ this.format }}</h1>
<h1>{{ this.format }}</h1>
<h1>{{ this.format }}</h1>
<h1>{{ this.format }}</h1>
<h1>{{ this.format }}</h1>

++ actions ++ (用于执行异步操作)

  • 定义
mutations: {
	add(state){
		state.count++
	}
}
actions: {
	addAsync(context){
		setTimeout(() => {
			context.commit('add')
		},1000)
	}
}
  • 触发
    • 方式1this.$store.dispatch('addAsync')
    • 方式2
import { mapActions } from 'vuex'
export default {
	name: 'app',
	methods: {
		...mapActions(['addAsync']),
		// this.addAsync()
	}
}
<button @click='addAsync'></button>

坚持就是胜利!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

微风拂晚霞

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

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

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

打赏作者

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

抵扣说明:

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

余额充值