$listeners和$attrs你会用了吗

275 阅读1分钟

一、之前没怎么使用过attrsattrs和listeners,最近用了一下,发现真香啊!现在就直接上干货吧。

//父组件
<template>
  <div class="">
    <myChild 
        v-model="value" 
        :maxlength="2000" 
        dataSon = 'dataSon' 
        dataSonSon = 'dataSonSon' 
        @mySonSonChange="mySonSonChange" 
        @mySonChagne="mySonChagne"/>
  </div>
</template>

<script>
import myChild from './attrsAndListenersChild'
export default {
  name: '',
  components:{
    myChild
  },
  data() {
    return {
      value:''
    }
  },
  methods: {
    mySonSonChange(){
      console.log('我是父组件的myChange,但是由我子组件的子组件调用')
    },
    mySonChagne(){
      console.log('我是父组件的myChange,但是由我子组件调用')
    }
  },
 }
</script>

<style lang="" scoped>
</style>
// 子组件
<template>
  <div class="">
    <el-input :value="value" v-bind="$attrs" v-on="$listeners"></el-input>
    <div>{{value.length}}/{{maxlength}}</div>
    <el-button type="primary" @click="sonClick">点击触发父组件的mySonChagne</el-button>
    <hr />
    <myChildSon v-bind="$attrs" v-on="$listeners"/>
  </div>
</template>

<script>
import myChildSon from './attrsAndListenersChildSon'
export default {
  name: '',
  components:{
    myChildSon
  },
  props:{
    value:{
      type:String
    },
    maxlength:{
      type:Number
    },
    dataSon:{
      type:String
    }
  },
  data() {
    return {

    }
  },
  methods:{
    sonClick(){
      this.$emit('mySonChagne')
    }
  },
  created () {
    // 传入的所有v-on事件都可以在$listeners对象中找到
    console.log(this.$listeners)//{mySonSonChange: ƒ, mySonChagne: ƒ, input: ƒ}
  }
 }
</script>

<style lang="" scoped>
</style>
//孙组件
<template>
  <div class="">
    <h1>这是来源于父组件的父组件的dataSonSon:{{dataSonSon}}</h1>
    <el-button type="primary" @click="sonSonCilck">点我触发父组件的父组件的mySonSonChange</el-button>
  </div>
</template>

<script>
export default {
  name: '',
  props:{
    dataSonSon:{
      type:String
    }
  },
  data() {
    return {

    }
  },
  methods:{
    sonSonCilck(){
      this.$emit('mySonSonChange')
    }
  },
  created () {
    // 传入的所有v-on事件都可以在$listeners对象中找到
    console.log(this.$listeners)//{mySonSonChange: ƒ, mySonChagne: ƒ, input: ƒ}
  }
 }
</script>

<style lang="" scoped>
</style>

从代码上可以看出,当使用$attrs时,组件就可以获取到父组件非Props传给子组件的值,同时孙组件也可以获取到父组件传给子组件的值。

在使用$listeners后,子组件和孙组件都可以触发父组件的方法,这就很美滋滋了。当我们在二次封装第三方组件时,这两个属性就非常有用了,我现在只是告诉大家如何使用,至于想要了解更多的可以去查看官方文档哦!!!!