Vue中$attrs与$listeners怎么使用

发布时间:2021-12-09 09:12:37 作者:iii
来源:亿速云 阅读:144

本篇内容主要讲解“Vue中$attrs与$listeners怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue中$attrs与$listeners怎么使用”吧!

介绍

$attrs

继承所有的父组件属性(没有通过 props 接收的属性还有 class 类名 和 style 样式 )。

inheritAttrs:

是否非 props 属性显示在标签最外层,默认值 true ,就是继承所有的父组件属性(除了 props 特定绑定外)作为普通的HTML特性应用在子组件的根元素上,如果你不希望组件的根元素继承特性就设置 inheritAttrs: false  ,但是 class 还是会继承。

$listeners

它是一个对象,能接收所有的方法绑定,里面包含了作用在这个组件上的所有监听器,配合 v-on="$listeners" 将所有的事件监听器指向这个组件的某个特定的子元素。

举例

父组件中 

<template>
  <div id="app">
    <Son src="https://img01.yzcdn.cn/vant/logo.png"></Son>
  </div>
</template>
 
<script>
import Son from "./components/son.vue";
export default {
  name: "App",
  components: {
    Son,
  },
};
</script>
 
<style></style>

子组件中

<template>
  <div id="app">
    <Son src="https://img01.yzcdn.cn/vant/logo.png"></Son>
  </div>
</template>
 
<script>
import Son from "./components/son.vue";
export default {
  name: "App",
  components: {
    Son,
  },
};
</script>
 
<style></style>

可见,当 inheritAttrs 默认 false 时,属性是传入到子组件最外层的

Vue中$attrs与$listeners怎么使用

当 inheritAttrs 为 true 后

Vue中$attrs与$listeners怎么使用

当使用props接收属性时,属性就不会被显示

Vue中$attrs与$listeners怎么使用

总结:组件标签上传入的属性如果子组件没有接收会跑到子组件标签最外层。

非 props 属性可以通过 $attrs 接收 {属性名:属性值}

<template>
  <div>
    <img v-bind="$attrs"  />
  </div>
</template>
 
<script>
export default {
  inheritAttrs: false,
};
</script>
<style scoped>
.img {
  width: 100px;
  height: 100px;
}
</style>

当给子组件绑定点击事件时,是不会触发点击事件的,可以使用 .native 修饰符进行绑定成功

Vue中$attrs与$listeners怎么使用

或者通过 $listeners 进行接收所有方法的绑定

子组件内

Vue中$attrs与$listeners怎么使用

结果

Vue中$attrs与$listeners怎么使用

到此,相信大家对“Vue中$attrs与$listeners怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. JMeter Listeners - Part 2: Listeners that Aggregate Data Samples
  2. JMeter Listeners - Part 1: Listeners with Basic Displays

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue attrs listeners

上一篇:RocketMQ中如何分析raft协议

下一篇:vscode中如何进行页面缩放和字体调整

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》