vue中使用v-bind=“$attrs“进行多层组件的传值&v-on=“$listener“监听事件(父级事件传递到内部组件)

一、使用v-bind="$attrs"进行多层组件的传值(即继承)

1、最外层组件(祖父)grandfather.vue

<template>
  <div class="grandfather">
  	<father :title="title"/>
  </div>
 </template>
 <script>
 export default {
 	data() {
 		return{
 			title: 'hello world!'
 		}
 	}
 }
 </script>

2、中间层组件(父亲)father.vue

<template>
  <div class="grandfather">
  	<children v-bind="$attrs"/>
  </div>
 </template>

3、最里层组件(儿子)children.vue

<template>
  <div class="grandfather">
  	{{title}}
  </div>
 </template>
 <script>
 export default {
 	props: {
 		title:{
 			type: String,
 			default: () => ''
 		}
 	}
 }
 </script>

这里则会取到title为 hello world!

二、v-on="$listener"监听事件(父级事件传递到内部组件)

1、最外层组件(祖父)grandfather.vue

<template>
  <div class="grandfather">
  	<father />
  </div>
 </template>
 <script>
 export default {
 	data() {
 		return{
 			title: 'hello world!'
 		}
 	},
 	methods:{
 		fun(){
			console.log(this.title)
		}
 	}
 }
 </script>

2、中间层组件(父亲)father.vue

<template>
  <div class="grandfather">
  	<children v-on="$listeners"/>
  </div>
 </template>

3、最里层组件(儿子)children.vue

<template>
  <div class="grandfather">
  </div>
 </template>
 <script>
 export default {
 	mounted(){
 		this.$listeners.fun() //会打印出hello world!
	}
 }
 </script>

总结

(1)v-bind="$attrs": 将调用组件时的组件标签上绑定的非props的特性(class和style除外)向下传递。在子组件中应当添加inheritAttrs: false(避免父作用域的不被认作props的特性绑定应用在子组件的根元素上)。

(2)3.v-on=“将父组件标签上的自定义事件向下传递其子组件可以直接通过emit(eventName)的方式调用。 vm.$listeners : 包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on=”$listeners" 传入内部组件——在创建更高层次的组件时非常有用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值