请问vue多级嵌套组件中v-bind=“$attrs“和v-on=“$listeners“有什么用?
网友回复
假设componentA调用componentB,而componentB又调用componentC
我们先看看componentA的代码,直接调用componentB,并给componentB传了值name age和 adress。
<componentB :name="_name" :age="_age" :address="_address" :phone="_phone" @playBall="_playBall" @study="_study" >而componentB只接受了name和age的传值,componentB 代码如下:
<template> <div></div> <componentC /> </template> <script> export default { indeterminate: true, props: { name, age }
另外ComponentB又调用了ComponentC, 若想在ComponentC获取ComponentA传输过来的没被ComponentB接收的非props数据,则组件ComponentB可以这么写:
<template> <div></div> <componentC v-bind="$attrs" v-on="$listeners" /> </template> <script> export default { indeterminate: true, props: { name, age }则在ComponentC中,可以通过vm.$attrs 获取祖先组件传输的数据, 通过vm.$listeners获取祖先节点的methods,栗子:
<template> </template> <script> export default { mounted () { // 访问ComponentA传入的`phone`, ComponentB的props并未接收 console.log(this.$attrs.phone) // 触发ComponentA绑定`study`事件, 并非ComponentB emit的 this.$emit('study') } }
总结:
1.v-bind="$props": 可以将父组件的所有props下发给它的子组件,子组件需要在其props:{} 中定义要接受的props。
vm.$props: 当前组件接收到的 props 对象。Vue 实例代理了对其 props 对象属性的访问。
2.v-bind="$attrs": 将调用组件时的组件标签上绑定的非props的特性(class和style除外)向下传递。在子组件中应当添加inheritAttrs: false(避免父作用域的不被认作props的特性绑定应用在子组件的根元素上)。
vm.$attrs :包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v
bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。
3.v-on="将父组件标签上的自定义事件向下传递其子组件可以直接通过emit(eventName)的方式调用。
vm.$listeners: 包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。
参考文章:https://blog.csdn.net/weixin_40825228/article/details/114700505