vuex state 实现组件间传值

本文介绍了如何通过Vuex来简化组件间状态传递,通过`npm add vuex`安装Vuex并在store.js中定义state。然后在组件中使用mapState辅助函数减少返回state值的代码。以一个实际案例展示:组件一点击确定将输入框内容传递给组件二。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

npm add vuex 下载vuex

store.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
	state:{
		name:jing,
		age:18,
		look:beautiful
	},
	mutations:{},
	actions:{}
})

组件一:

<div>
	name:{{username}}
	<button @click="add"> 确认</button>
</div>
data(){
	return(){
		//注意 写在data中,因为先赋值给了username,那么store值如有改变,这里将不能发生改变
		// username:this.$store.state.name 
	}
},
computed:{
	username(){
		return this.$store.state.name
	}
}
methods:{
	add(){
		this.$store.state.name = 'jing+1'
	}
}

组件二:

<div>
	name02:{{$store.state.name}}
</div>

但如果sore中有许多的值需要获取就得写很多的 return,有没有更方便的办法呢?
在组件中引入 mapState:

import {mapState} from 'vuex'
//1
computed:mapState(['name','age','look']),
//2
computed:mapState({
	storeName:state => state.name,
	storeAge:state => state.age,
	storeLook:state => state.look
})
//但computed也有自己的运算函数,就不能写1、2这样了
computed:{
	...mapState({
		storeName:state => state.name,
		storeAge:state => state.age,
		storeLook:state => state.look
	})
}

<div>
	name:{{storeName}}
	age:{{storeAge}}
	look:{{storeLook}}
</div>

.
案例:组件一 点击确定将输入框的内容添加到组件二中。

store.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
	state:{
		studentList:[]
	},
	mutations:{},
	actions:{}
})

组件一:

<div>
	name:
	<input type="text" v-model="name">
	<button @click="add"> 确认</button>
</div>
export default({
	data(){
		return(){
			name:''
		}
	}
	methods:{
		add(){
			this.$store.state.studentList.push(this.name);
		}
	}
})

组件二:

<div>
	namelist:
	<ul>
		<li v-for="(item, index) in studentList" :key="index">
			{{item}}
		</li>
	</ul>
</div>
import {mapState} from 'vuex'
export default({
	computed:{
		...mapState(['studentList'])
	}
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值