vue父子组件间引用之$parent、$children

vue中提到【父子组件】,则一定会想到我们常用的父子组件通信:props+$on()$emit() ,如图:

有时候我们需要父组件直接访问子组件、子组件直接访问父组件,或者子组件访问根组件:

  • 父组件访问子组件:使用$children$refs reference
  • 子组件访问父组件:使用$parent

父子组件的访问方式之:$children

children很特别,查阅资料可以发现:this.$children是一个数组类型,它包含了所有子组件对象:

<body>
		<div id="app">
			<mxc></mxc>
			<mxc></mxc>
			<mxc></mxc>
			<button @click="btnClick">颤抖吧</button>
		</div>
		<template id="mxc">
			<div>我是子组件啊</div>
		</template>
		
		<script>
			const app=new Vue({
				el:'#app',
				data:{
					message:'你好'
				},
				methods:{
					btnClick(){
						console.log(this.$children)
					}
				},
				components:{
					mxc:{
						template:'#mxc',
						methods:{
							showMessage(){
								console.log('mxcnb')
							}
						}
					}
				}
			})
		</script>
	</body>

点击(父组件)按钮之后:

因为是数组,所以我们可以通过比如:this.$children[2]来拿到第三个子组件的数据。
但是这么做有一个问题:比如开发时突然在这三个子组件中又插入了一个子组件(可能相同,也可能不同),这时候【2】就不再是我们需要的了。。。

所以我们可以用vue-DOM之光$refs

<body>
		<div id="app">
			<mxc></mxc>
			<mxc></mxc>
			<mxc ref="aaa"></mxc>
			<button @click="btnClick">颤抖吧</button>
		</div>
		<template id="mxc">
			<div>我是子组件啊</div>
		</template>
		
		<script>
			const app=new Vue({
				el:'#app',
				data:{
					message:'你好'
				},
				methods:{
					btnClick(){
						console.log(this.$refs)
						console.log(this.$refs.aaa)
					}
				},
				components:{
					mxc:{
						template:'#mxc',
						data(){
							return{
								name:'我是子组件的name'
							}
						},
						methods:{
							showMessage(){
								console.log('mxcnb')
							}
						}
					}
				}
			})
		</script>
	</body>

点击(父组件)按钮之后:

图中el属性在有些浏览器(或添加了vue插件)会显示未Vue?
因为当前子组件的父组件就是vue实例啊!

(但是在实际中$parent用的非常少——考虑到耦合度的原因)

子组件访问根组件:$root

<body>
		<div id="app">
			<mxc></mxc>
		</div>
		<template id="mxc">
			<div>
				<div>我是mxc组件</div>
				<cdn></cdn>
			</div>
		</template>
		<template id="mxca">
			<div>
				<div>我是子子组件啊</div>
				<button @click="btnClick">巨颤祖child</button>
			</div>
		</template>
		
		<script>
			const app=new Vue({
				el:'#app',
				data:{
					message:'你好'
				},
				components:{
					mxc:{
						template:'#mxc',
						data(){
							return{
								name:'我是中间子组件的name'
							}
						},
						components:{
							cdn:{
								template:'#mxca',
								methods:{
									btnClick(){
										console.log(this.$parent.name)
										console.log(this.$root.message)
									}
								}
							}
						}
					}
				}
			})
		</script>
	</body>

xs

总结

到此这篇关于vue父子组件间引用:$parent、$children的文章就介绍到这了,更多相关vue父子组件间引用:$parent、$children内容请搜索来客网以前的文章或继续浏览下面的相关文章希望大家以后多多支持来客网!