Migrating to Vue3 How can I have attributes on a component's root element and native event listeners on a child element? #9004
-
I need to have attributes including classes and general attributes in a root element and extract all native events on a child element in a component. According to the new Vue3 documentation, there should be some workaround with that since now we have only I have a simple example of Vue2 code in the template block
How do I migrate this to Vue3? I'm expecting to have attributes on a component's root element and all native events on a child element |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
<button v-bind="$attrs"></button> |
Beta Was this translation helpful? Give feedback.
-
// Comp.vue
<script setup lang="ts">
import {useAttrs,toRefs,toValue,computed} from 'vue'
defineOptions({
inheritAttrs: false
})
const attrs = useAttrs()
const attributes = computed(() => omit(attrs, (k,v) => k.startsWith('on')))
const events = computed(() => omit(attrs,(k,v) => !k.startsWith('on')))
// Quoted from @vueuse
// https://vueuse.org/shared/reactiveOmit/#reactiveomit
function omit(obj, predicate){
return Object.fromEntries(Object.entries(obj).filter(([k, v]) => !predicate(k, v)))
}
console.log(attrs,attributes,events)
</script>
<template>
<div v-bind="attributes">
<span>click background</span>
<button v-bind="events">
click button
</button>
</div>
<br>
<div v-bind="attrs">
<span>click background</span>
<button v-bind="attrs">
click button
</button>
</div>
</template>
// App.vue
<script setup lang="ts">
import { ref } from 'vue'
import Comp from './Comp.vue'
const style = ref('color:red;background-color:#EEE')
const handler = () => {
console.log('Comp:click')
}
</script>
<template>
<input type="text" v-model="style" />
<br>
<Comp :style="style" @click="handler"></Comp>
</template> |
Beta Was this translation helpful? Give feedback.
playground