欢迎来到代码驿站!

vue

当前位置:首页 > 网页前端 > vue

简单聊聊vue2.x的$attrs和$listeners

时间:2022-10-06 12:00:53|栏目:vue|点击:

$attrs

$attrs 用于多层次组件传递参数(组件标签的attribute,class和style除外),爷爷辈组件向孙子辈组件传递参数(注:参数不能被父辈prop识别,一旦被父辈prop识别且获取,则孙子辈组件不能获取到该参数)

写法如下:(注:v-bind不能用简写 :)

<grand-son v-bind="$attrs" />

下面举个栗子:

爷爷(GrandFather)向父亲(Father)传递一个 msg1

向孙子(GrandSon)传递一个 msg2,孙子会一并接收 msg1(然而被父亲接走了,所以孙子收不到 msg1)

<!-- GrandFather.vue -->
<template>
  <div>
    GrandFather:
    <father :msg1="msg1" :msg2="msg2" />
  </div>
</template>

<script>
import Father from './Father.vue'
export default {
  components: { Father },
  data() {
    return {
      msg1: 'msg1',
      msg2: 'msg2'
    }
  }
}
</script>
<!-- Father.vue -->
<template>
  <div>
    Father: {{ msg1 }}
    <grand-son v-bind="$attrs" />
  </div>
</template>

<script>
import GrandSon from './GrandSon.vue'
export default {
  components: { GrandSon },
  props: ['msg1']
}
</script>
<!-- GrandSon.vue -->
<template>
  <div>GrandSon: {{ msg1 }}{{ msg2 }}</div>
</template>

<script>
export default {
  props: ['msg1', 'msg2']
}
</script>

界面现实结果:

GrandFather:
Father: msg1
GrandSon: msg2

$listeners

$listeners 用于多层次组件传递事件监听器,爷爷辈组件向父辈、孙子辈、曾孙子辈……组件传递事件(与 $attrs 不同,不存在半路被拦截的情况)

写法如下:(注:v-on 不能用简写 @,虽然不报错,但是也不生效)

<grand-son v-on="$listeners" />

下面继续使用 爷爷-> 父亲 -> 孙子 的栗子:

爷爷(GrandFather)给父亲(Father)绑定一个 click 事件

父亲通过点击 div 触发 click 事件,同时向孙子(GrandSon)传递 $listeners

<!-- GrandFather.vue -->
<template>
  <div>
    GrandFather:
    <father :msg1="msg1" :msg2="msg2" @click="handleClick" />
  </div>
</template>

<script>
import Father from './Father.vue'
export default {
  components: { Father },
  data() {
    return {
      msg1: 'msg1',
      msg2: 'msg2'
    }
  },
  methods: {
    handleClick() {
      console.log('trriger click')
    }
  }
}
</script>
<!-- Father.vue -->
<template>
  <div>
    <div @click="handleFatherClick">Father: {{ msg1 }}</div>
    <grand-son v-bind="$attrs" v-on="$listeners" />
  </div>
</template>

<script>
import GrandSon from './GrandSon.vue'
export default {
  components: { GrandSon },
  props: ['msg1'],
  methods: {
    handleFatherClick() {
      console.log('father click')
      this.$emit('click')
    }
  }
}
</script>
<!-- GrandSon.vue -->
<template>
  <div @click="handleSonClick">GrandSon: {{ msg1 }}{{ msg2 }}</div>
</template>

<script>
export default {
  props: ['msg1', 'msg2'],
  methods: {
    handleSonClick() {
      console.log('grandson click')
      this.$emit('click')
    }
  }
}
</script>

界面:

GrandFather:
Father: msg1
GrandSon: msg2

点击 Father: msg1,控制台显示:

father click
trriger click

点击 GrandSon: msg2,控制台显示:

grandson click
trriger click

总结

上一篇:Vue3使用icon的两种方式实例

栏    目:vue

下一篇:没有了

本文标题:简单聊聊vue2.x的$attrs和$listeners

本文地址:http://www.codeinn.net/misctech/215655.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有