Skip to content

Migrating to Vue3 How can I have attributes on a component's root element and native event listeners on a child element? #9004

Discussion options

You must be logged in to vote

playground

// 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
    </b…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@daniilgri
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by daniilgri
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants