# 移除 $listeners
非兼容
# 概览
$listeners 对象在 Vue 3 中已被移除。现在事件监听器是 $attrs 的一部分:
{
text: 'this is an attribute',
onClose: () => console.log('close Event triggered')
}
1
2
3
4
2
3
4
# 2.x 语法
在 Vue 2 中,你可以使用 this.$attrs 和 this.$listeners 分别访问传递给组件的 attribute 和事件监听器。结合 inheritAttrs: false,开发者可以将这些 attribute 和监听器应用到其它元素,而不是根元素:
<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
2
3
4
5
6
7
8
9
10
# 3.x 语法
在 Vue 3 的虚拟 DOM 中,事件监听器现在只是以 on 为前缀的 attribute,这样就成了 $attrs 对象的一部分,因此 $listeners 被移除了。
<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
2
3
4
5
6
7
8
9
10
如果这个组件接收一个 id attribute 和一个 v-on:close 监听器,那么 $attrs 对象现在将如下所示:
{
id: 'my-input',
onClose: () => console.log('close Event triggered')
}
1
2
3
4
2
3
4
# 迁移策略
删除所有的 $listeners 用法。