Vue父子组件传值

Vue父子组件传值

加粗样式父组件向子组件传值:
在组件中,使用选项props来声明从父级组件接收的数据,props的值可以是两种,一种是字符串数组,一种是对象。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>父组件向子组件传值</title>
	</head>
	<body>
		<!-- 父组件显示 -->
		<template id="parent1">
			<h4>{{message}}</h4>
		
			<!-- 使用v-bind将父组件parent的data(posts)动态传递给props,children组件只能在parent中 -->
			<children v-for="post in posts" :id="post.id" :title="post.title"></children>
			<!-- 将一个对象的所有属性都作为props传入,与上面一句等价 -->
			<children v-for="post in posts" v-bind="post"></children>
		</template>
		<!-- 子组件显示 -->
		<template id="children">
			<h4>{{id}} : {{title}}</h4>
		</template>
		<div id="message-post-demo">
			<!-- 静态传递字符串,父组件就是当前的实例 -->
<parent message="来自父组件的消息"></parent>
		</div>
	</body>
</html>
<script src="vue.global.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
	const messageApp = Vue.createApp({})
	messageApp.component('parent', {
		data() {
			return {
				posts: [{
						id: 1,
						title: 'My journey with Vue'
					},
					{
						id: 2,
						title: 'Blogging with Vue'
					},
					{
						id: 3,
						title: 'Why Vue is so fun'
					}
				]
			}
		},
		props:['message'],//接收父组件messageApp传递的数据
		components:{
			//创建子组件children
			'children':{
				props:['id','title'],//接收父组件parent传递的数据
				template:'#children'
			}
		},
		template:'#parent1'
	})
	messageApp.mount('#message-post-demo')
</script>

在这里插入图片描述

使用v-model实现子组件向父组件传值,并实现双向绑定。
子——>父时,先给子组件自定义事件并使用$emit(‘事件名’,要传递的数据)方法触发事件,然后父组件使用v-on或@监听子组件的事件。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>子组件向父组件传值</title>
	</head>
	<template id="custom">
		<!-- 为了让子组件正常工作,子组件内的<input>必须将其value属性绑定到一个名为modelValue的props上,在其input事件被触发时,将新的值通过自定义的update:value事件传递 -->
		<input :value="modelValue" @input="$emit('update:modelValue',$event.target.value)" />
	</template>
	<div id="vmode-post-demo">
		{{searchText}}<br>
		<custom-input v-model="searchText"></custom-input><br>
		<!-- 这两个子组件相等 -->
		<custom-input :model-value="searchText" @update:model-value="searchText=$event"></custom-input>
	</div>
	<body>
	</body>
</html>
<script src="vue.global.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
	const blogApp = Vue.createApp({
		data() {
			return {
				searchText: '大帅逼'
			}
		}
	})
	blogApp.component('custom-input', {
		props: ['modelValue'],
		template: '#custom'
	})
	blogApp.mount('#vmode-post-demo')
</script>

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值