vue中关于 vuex的取值传值

commit 同步操作
改变流程: 页面触发 — mutations — state

存储:

1.只有一个根文件(index.js)
this.$store.commit('名称',传入的值) 
2.  模块化时:
this.$store.commit('文件名+mutations中的函数名',传入的值)
例如:this.$store.commit('area/SET_NAME','我是三九感冒灵')

取值:

1.只有一个根文件时
this.$store.state.属性名
2.this.$store.state.文件名.属性名
例如:this.$store.state.area.name

dispatch 异步操作
改变流程: 页面触发 — actions — mutations — state

存储:

1.只有一个根文件(index.js)
this.$store.dispatch('名称',传入的值) 
2.  模块化时:
this.$store.dispatch('文件名+mutations中的函数名',传入的值)
例如:this.$store.dispatch('area/getRoles','我是三九感冒灵')

取值

1.只有一个根文件时
this.$store.getters.属性名
2.模块化时
this.$store.getters.属性名
例如:this.$store.getters

在这里插入图片描述

Vue使用Vuex进行状态管理是非常常见的,它可以帮助我们更好地组织和管理应用程序的状态。下面是一个简单的例子,演示如何在Vue使用Vuex进行传值。 1. 安装Vuex 首先,我们需要安装Vuex。可以使用npm或yarn来安装: ``` npm install vuex --save ``` 或者 ``` yarn add vuex ``` 2. 创建store 在Vue使用Vuex需要先创建一个store。在store,我们可以定义和管理应用程序的所有状态。 ``` import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } } }); export default store; ``` 在这个例子,我们定义了一个名为“count”的状态和一个名为“increment”的mutation,当我们调用“increment”mutation时,它会增加“count”状态的值。 3. 在Vue组件使用store 现在我们已经创建了一个store,接下来让我们在Vue组件使用它。我们需要使用Vuex提供的“mapState”和“mapMutations”辅助函数来访问store的状态和mutations。 ``` <template> <div> <h1>{{ count }}</h1> <button @click="increment">Increment</button> </div> </template> <script> import { mapState, mapMutations } from 'vuex'; export default { computed: { ...mapState(['count']) }, methods: { ...mapMutations(['increment']) } } </script> ``` 在这个例子,我们使用了“mapState”辅助函数来将“count”状态映射到组件的计算属性,并使用“mapMutations”辅助函数将“increment”mutation映射到组件的方法。这样,在组件就可以直接使用“count”状态和“increment”mutation了。 以上就是使用Vuex进行状态管理的基本过程。在实际开发,我们通常需要定义更多的状态和mutations,并使用actions和getters等高级特性来管理更复杂的状态。但基本的使用方法和原理都是相似的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值