I am migrating vue 2 application to vue 3. In official docs, it is mentioned that $listeners object has been removed in Vue 3. Event listeners are now part of $attrs. It is taking non-prop attributes (class, style) as well. In my vue 2 application, there is one icon-button custom component and it is looking like this below.
Icon-component:
<template>
<vu-button v-bind="buttonProps"
:class="buttonClass"
v-on="$listeners"
@click="buttonToggle">
<vu-icon v-bind="iconProps"><slot/></vu-icon>
</vu-button>
</template>
It is used in various other components.
Parent component 1:
<vu-icon-button id="sw1" medium style="left:200px;">home</vu-icon-button>
Parent component 2:
<vu-icon-button class="menu-detail-btn" icon="collapse_menu" icon-type="su" @click="openModal()" size="small"></vu-icon-button>
As of migration strategy, i removed the $listeners but not sure about those non-prop attributes and v-bind tag. How to modify those so it can be used in parent component with attributes?
You can access a component's fallthrough attributes in
<script setup>using theuseAttrs()API:
<script setup>
import { useAttrs } from 'vue'
const attrs = useAttrs()
</script>
If not using <script setup>, attrs will be exposed as a property of the setup() context:
export default {
setup(props, ctx) {
// fallthrough attributes are exposed as ctx.attrs
console.log(ctx.attrs)
}
}
If you do not want a component to automatically inherit attributes, you can set inheritAttrs: false in the component's options.
If using <script setup>, you will need to declare this option using a separate, normal <script> block:
<script>
// use normal <script> to declare options
export default {
inheritAttrs: false
}
</script>
<script setup>
// ...setup logic
</script>
You can now use the $attrs object directly in the template. This is useful when you want to bind the attribute to a non-root element of your choice, as opposed to the automatic behaviour of attributes being inherited by the root element.
Example:
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With