vue11--组件之间的通信--子组件往父组件传值(不可自动触发)

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>组件之间的通信--子组件往父组件传值(不可自动触发)</title>
		<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
	</head>

	<body>
		<div id="app">
			子组件往父组件传值
			<father></father>
		</div>

		<template id="father">
			<div>
				<p>这是父组件</p>
				<p>来自于子组件的数据:{
   
   {sondata}}</p>
				<son @get-info="get"></son>
			</div>
		</template>

<!--
	子组件向父组件传值:
	1.子组件中必须时间出发去传值
	2.子组件定义时,触发事件的属性名必须是xxx-xxx的形式
	3.子组件定义时,触发父组件执行的函数名的声明部分不能加()
	
-->

		<template id="son">
			<div>
				这是子组件
				<div>
					电话号码:<input type="text" v-model="tel" />
				</div>
				<div>
					<button type="button" @click="sendInfo()">传值</button>
				</div>
			</div>
		</template>

		<script>
			let vm = new Vue({
				el: '#app',
				components: {
					'father': {
						template: '#father',
						data() {
							return {
								sondata: ''
							}
						},
						components: {
							'son': {
								template: '#son',
								data() {
									return {
										tel: ''
									}
								},
								methods: {
									sendInfo() { //进入子组件的send方法
										this.$emit('get-info', this.tel);
									}
								}
							}
						},
						methods: {
							get(tel) { //进入父组件get方法
								this.sondata = tel;
							}
						}
					}
				}
			});
		</script>
	</body>

</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/gcyqweasd/article/details/113799130
今日推荐