VUE3-组件之间传值《四》

目录

一.父传子,父组件向子组件传值

二.子传父,子组件向父组件传值

三.兄弟组件之间互传,2个组件之间是平级关系,互相传值


组件之间的传值,分为3种方式

一.父传子,父组件向子组件传值

1.建立一个默认的vue3程序,运行起来如图所示

2.此例子其实就是一个默认的父传子组件

父组件就是App.vue

子组件就是HelloWorld.vue

在父组件App.vue中引用了HelloWorld子组件,只需要把子组件中的msg变量绑定一个a的变量即可

<script setup>
	// This starter template is using Vue 3 <script setup> SFCs
	// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
	import HelloWorld from './components/HelloWorld.vue'
	let a = '父传子的值'
</script>

<template>
	<img alt="Vue logo" src="./assets/logo.png" />
	<HelloWorld :msg="a" />
</template>

<style>
	#app {
		font-family: Avenir, Helvetica, Arial, sans-serif;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		text-align: center;
		color: #2c3e50;
		margin-top: 60px;
	}
</style>

3.在子组件中,把不需要的代码删除

<template>
	<h1>{
   
   { msg }}</h1>
</template>
<script setup>
	defineProps({
		msg: String
	})
</script>
<style scoped>

</style>

4.运行效果,可以看到父组件中的值,已经显示到了子组件中。

补充另一种,其实就是provide和inject,还使用上面的项目的结构

传值。App.vue是父

<script setup>
	// This starter template is using Vue 3 <script setup> SFCs
	// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
	import HelloWorld from './components/HelloWorld.vue'
	import {
		provide
	} from 'vue'

	provide("msg", "给子孙的数据") //向下传递数据
</script>

<template>
	<img alt="Vue logo" src="./assets/logo.png" />
	<HelloWorld />
</template>

<style>
	#app {
		font-family: Avenir, Helvetica, Arial, sans-serif;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		text-align: center;
		color: #2c3e50;
		margin-top: 60px;
	}
</style>

接收值。HelloWorld.vue是子

<script setup>
	import {
		inject
	} from 'vue'

	const msg = inject("msg")
	console.log(msg)
</script>

<template>
	<h1>{
   
   { msg }}</h1>
</template>

<style scoped>
	a {
		color: #42b983;
	}
</style>

 效果

二.子传父,子组件向父组件传值

1.先在子组件中写一个点击事件,再定义emit,emit的第一个参数是父组件的方法,第二参数就是需要传递的值。

<template>
	<button @click="send">点击向父组件传值</button>
</template>
<script setup>
	const emit = defineEmits(['aa'])
	const send = () => {
		emit("aa", "点击向父组件传值");
	}
</script>
<style scoped>

</style>

2.在父组件中,接收方法aa,然后再定义bb,最后输出data的值,就是传递的值 

3.运行效果,点击子组件的值,可以在父组件中看到输出的值。

三.兄弟组件之间互传,2个组件之间是平级关系,互相传值

在vue3之前,可以使用事件总线,但是vue3中,官方已经把事件总线删除了,所以就不能使用了。

其实兄弟组件也可以转化成子传父,然后父传子,2个组件都去寻找同一个父组件,然后进行传值,不过这样太麻烦了,没有必要。

vue3中使用pinia更加的简单方便,不管你什么子组件,父组件,都可以互相传值,各个组件之间都可以互相传值,没有任何限制。参考链接如下,包括上面的父传子,子传父的问题,都可以使用pinia,所以强烈推荐使用。

VUE3-Pinia的使用《三》_故里2130的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/u012563853/article/details/128397775