【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>
 
原文地址:https://www.cnblogs.com/xiaohuizhang/p/13793540.html