vue $listeners $attrs使用场景

关系图:在这里插入图片描述

a t r r s : 包含父作用域中不作为 p r o p s 被试别(且获取)的特性绑定( c l a s s 、 s t y l e 除外),当一个组件没有声明任何 p r o p s 时,这里会包含所有父作用域的绑定( c l a s s 、 s t y l e 除外),且通过 v − b i n d = " atrrs:包含父作用域中不作为props被试别(且获取)的特性绑定(class、style除外),当一个组件没有声明任何props时,这里会包含所有父作用域的绑定(class、style除外),且通过v-bind=" atrrs:包含父作用域中不作为props被试别(且获取)的特性绑定(classstyle除外),当一个组件没有声明任何props时,这里会包含所有父作用域的绑定(classstyle除外),且通过vbind="atrrs"传入父组件【父传孙专用,对于值】

l i s t e n e r s : 包含作用域中(不含 . n a t i v e 修饰器的) v − o n 事件监听,可以通过 v − o n = " listeners: 包含作用域中(不含.native修饰器的)v-on事件监听,可以通过v-on=" listeners:包含作用域中(不含.native修饰器的)von事件监听,可以通过von="listeners"传入内部组件【孙传父专用,对于事件】

A:父组件

<template>
    <div id="father">
        father {{tempdata1}}-{{tempdata2}}
        <button @click="fu">fu</button>
        <child :temp1="tempdata1" :temp2="tempdata2" @tempFn="fahterFn" :propsValue="propsValue"></child>
    </div>
</template>

<script>
import child from './child.vue';
export default {
  components: { child },

  data() {
      return {
          tempdata1: 'father1',
          tempdata2: 'father2',
          propsValue: '$attrs不会传递child组件中定义的props值'
      }
  },

  created() {},
  mounted() {},

  computed: {},

  watch: {},

  methods: {
      fahterFn(val1,val2) {
          this.tempdata1 = val1;
          this.tempdata2 = val2;
          console.log('father function!',val1);
      },
      fu() {
          this.tempdata1 = 'xixixi'
      }
  },
};
</script>

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

B:子组件

<template>
    <div id="child">
        <div>
            child: {{$attrs}}-{{propsValue}}
        </div>
        <son v-bind="$attrs" v-on="$listeners"></son>
    </div>
</template>

<script>
import son from './son.vue';
export default {
  components: { son },
  props: ['propsValue'],

  data() {
      return {

      }
  },

  created() {},
  mounted() {},

  computed: {},

  watch: {},

  methods: {
  },
};
</script>

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

C:孙组件

<template>
    <div id="son">
        son {{$attrs}}
        <button @click="ab">dd</button>
    </div>
</template>

<script>
export default {
  components: {},

//   props : ['temp1','temp2'],  //如果不用$attrs的话可以采用props来接受,这样可以对 temp1、temp2字段的监听操作

  data() {
      return {

      }
  },

  created() {},
  mounted() {
    //   console.log("son=--this.$attrs",this.$attrs);
    //  console.log("son-0000this.$listeners",this.$listeners);
  },

  computed: {},

  watch: {},

  methods: {
      ab() {
        //   this.$listeners.tempFn('dfdf','125')  //这两种方法都可以,实现
        this.$emit('tempFn','dfdf','125');
      }
  },
};
</script>

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

在这里插入图片描述
点击fu
在这里插入图片描述
点击dd
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值