$listeners 已移除 重大变更
概述
$listeners 对象已在 Vue 3 中移除。事件监听器现在是 $attrs 的一部分。
js
{
text: 'this is an attribute',
onClose: () => console.log('close Event triggered')
}2.x 语法
在 Vue 2 中,您可以使用 this.$attrs 访问传递给组件的属性,使用 this.$listeners 访问事件监听器。结合 inheritAttrs: false,它们允许开发人员将这些属性和监听器应用于其他元素,而不是根元素。
html
<template>
<label>
<input type="text" v-bind="$attrs" v-on="$listeners" />
</label>
</template>
<script>
export default {
inheritAttrs: false
}
</script>3.x 语法
在 Vue 3 的虚拟 DOM 中,事件监听器现在只是属性,以 on 为前缀,因此是 $attrs 对象的一部分,因此 $listeners 已被移除。
vue
<template>
<label>
<input type="text" v-bind="$attrs" />
</label>
</template>
<script>
export default {
inheritAttrs: false
}
</script>如果此组件接收了 id 属性和 v-on:close 监听器,$attrs 对象现在将如下所示
js
{
id: 'my-input',
onClose: () => console.log('close Event triggered')
}迁移策略
移除所有 $listeners 的使用。