首页 > 技术文章 > <vue 组件 3、父子组件相互访问>

yclh 2021-11-19 16:40 原文

代码结构

 

 

一、     01-组件访问-父访问子

1、 效果  

点击后在父组件里展示子组件的参数

 

 

2、代码

01-组件访问-父访问子.html

 

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
	</head>
	<body>

		<div id="app">
			<cpn ref="zi"></cpn>
			<div>--------------------</div>
			<div>我是父组件 </div>
			<button @click="btnClick">按钮</button>
			<div>
				{{ziName}}
			</div>
		</div>

		<template id="cpn">
			<div> 子组件name: {{name}} </div>
			 
		</template>
		
		<script src="vue.js"></script>
		<script>
			let app = new Vue({
				el: '#app',
				data: {
					message: '你好',
					ziName:'父组件名称的初始值'
				},
				methods: {
					btnClick() {
						//$refs => 对象类型 
						this.ziName = this.$refs.zi.name;
					}
				},
				components: {
					cpn: {
						template: '#cpn',
						data() {
							return {
								name: '我是子组件的name',
							}
						} 
					} 
				}
			})
		</script>

	</body>
</html>

 

 

二、     02-组件访问-子访问父

1、 效果

点击后在子组件中访问了父组件和根组件的参数

 

 

2、代码

02-组件访问-子访问父.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
	</head>
	<body>

		<div id="app">
			<h2>我是根组件</h2>
			 <h2>---------</h2>
			<cpn></cpn>
		</div>

		<template id="cpn">
			<div>
				<h2>我是父组件</h2>
				<h2>---------</h2>
				<ccpn></ccpn>
				
			</div>
		</template>

		<template id="ccpn">
			<div>
				<h2>我是子组件</h2>
				<button @click="btnClick">按钮</button>
			</div>
		</template>

		<script src="vue.js"></script>
		<script>
			let app = new Vue({
				el: '#app',
				data: {
					message: '我是根组件!'
				},
				components: {
					cpn: {
						template: '#cpn',
						data() {
							return {
								name: '我是父组件的name'
							}
						},
						components: {
							ccpn: {
								template: '#ccpn',
								methods: {
									btnClick() {
										// 1.访问父组件$parent
										// console.log(this.$parent);
										  console.log(this.$parent.name);

										// 2.访问根组件$root
										//console.log(this.$root);
										console.log(this.$root.message);
									}
								}
							}
						}
					}
				}
			})
		</script>

	</body>
</html>

 

推荐阅读