vue中$attrs $listeners 的简单使用

Ex : A 包含 B  B包含C

简单来说:$attrs 与 $listeners 是两个「对象」,$attrs 里存放的是父组件中绑定的非 Props 属性,$listeners里存放的是父组件中绑定的非原生事件。

A组件:

<template>

  <div>

    <button @click="add">点击增加年龄</button>

    <child :title="title"

           :name='name'

           :hobby='hobby'

           :age='age'

           @childclik='childclik'

           />

  </div>

</template>

<script>

  import child from './child'

  export default {

    components: { child },

    data () {

      return {

        title: '自我介绍',

        name: 'Tom',

        hobby: 'like eat',

        age: 4,

      }

    },

    methods: {

      add () {

        this.age++

      },

      childclik(val){

          this.name=val

      }

    },

  }

</script>

B组件:

<template>

  <section>

    <div>我是子组件:{{$attrs}}</div>

    <childChild v-bind="$attrs" />

    <el-button @click="$listeners.childclik('xxxxxxxx')">子组件的方法</el-button>

  </section>

</template>

<script>

  import childChild from './childlittle'

  export default {

    props: [],

    components: {

      childChild

    }

  }

</script>

C组件:

<template>

    <div style="width:100%;marign-top:50px;padding:30px;background:gray">

         <div>我是子组件的组件:

           </div>

         <div>主题:{{$attrs.title}}</div>

         <div>姓名:{{$attrs.name}}</div>

         <div>爱好:{{$attrs.hobby}}</div>

         <div>年龄:{{$attrs.age}}</div>

    </div>

</template>

效果图:

点击【子组件的方法】

简单来说:$attrs 与 $listeners 是两个「对象」,$attrs 里存放的是父组件中绑定的非 Props 属性,$listeners里存放的是父组件中绑定的非原生事件。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容