【vue开发】v-bind="$attrs" v-on="$listeners" 多层组件监听

多级组件通信,用vuex太重,props太麻烦。

vue 2.4 版本提供了另一种方法,使用 v-bind=”$attrs”, 将父组件中不被认为 props特性绑定的属性传入子组件中,通常配合 interitAttrs 选项一起使用。

<top>
    <center>
        <bottom>
        </bottom>
    </center>
</top>

需求:1、top和bottom间进行通信 props和$emit,需要center作为中转 

           2、vuex确定是全局状态?


下面是详细用法:

复制代码
<top @getDataList ="getDataList" :yes="123"><top>
 
//    .native绑原生事件是没用的
<center v-on="$listeners" v-bind="$attrs"></center>
 
//在bottom组件中,可以直接调用getDataList这个方法
export default {
  name: 'index',
  props: ['yes'],
  inheritAttrs: false,
  methods: {
    doClick(data) {
      console.log(this.yes) //    123, top组件中传递下来的props(center中props声明过的除外)
      this.$emit('getListData', data)
    }
  }
}
//  inheritAttrs:默认值true,继承所有的父组件属性(除props的特定绑定)作为普通的HTML特性应用在
//  子组件的根元素上,如果你不希望组件的根元素继承特性设置inheritAttrs: false,但是class属性会继承
</script>
 
复制代码

 

posted @   JeckHui  阅读(779)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示