vuejs 教程,vue3.0 文档,vuejs 实战,前端框架,vuejs 入门,vue3.0 迁移,vue3资讯,Vue3最新动态,vuejs 中文社区,javascript中文网,vuejs 面试题,vuejs bug

# $listeners removed
非兼容

# Overview

The $listeners object has been removed in Vue 3. Event listeners are now part of $attrs:

{
  text: 'this is an attribute',
  onClose: () => console.log('close Event triggered')
}
1
2
3
4

# 2.x Syntax

In Vue 2, you can access attributes passed to your components with this.$attrs, and event listeners with this.$listeners. In combination with inheritAttrs: false, they allow the developer to apply these attributes and listeners to some other element instead of the root element:

<template>
  <label>
    <input type="text" v-bind="$attrs" v-on="$listeners" />
  </label>
</template>
<script>
  export default {
    inheritAttrs: false
  }
</script>
1
2
3
4
5
6
7
8
9
10

# 3.x Syntax

In Vue 3's virtual DOM, event listeners are now just attributes, prefixed with on, and as such are part of the $attrs object, so $listeners has been removed.

<template>
  <label>
    <input type="text" v-bind="$attrs" />
  </label>
</template>
<script>
export default {
  inheritAttrs: false
}
</script>
1
2
3
4
5
6
7
8
9
10

If this component received an id attribute and a v-on:close listener, the $attrs object will now look like this:

{
  id: 'my-input',
  onClose: () => console.log('close Event triggered')
}
1
2
3
4

# Migration Strategy

Remove all usages of $listeners.

# See also

Js中文网,专注分享前端最新技术、大厂面试题、聊点程序员轶事、职场感悟,做前端技术的传播者.

加入前端布道师交流群

扫描二维码回复 加群 学习,与大厂大佬讨论技术.