[Vuejs]-Pass specific $attrs parameter to Vue component

0๐Ÿ‘

โœ…

If you know what attributes are for div element then you should use them as props instead of $attrs.

or you can split $attrs

<template>
<div v-bind="divAttrs">
   <h1 v-bind="h1Attrs">{{post.id}}</h1>
</div>
</template>
<script>
export default {
   computed: {
     divAttrs () {
       const allowed = ['data-status', 'data-feature']
       return Object.keys(this.$attrs)
         .filter(key => allowed.includes(key))
         .reduce((obj, key) => {
           obj[key] = this.$attrs[key]
           return obj
         }, {})
     },
     h1Attrs () {
       const notAllowed = ['data-status', 'data-feature']
       return Object.keys(this.$attrs)
         .filter(key => !notAllowed.includes(key))
         .reduce((obj, key) => {
           obj[key] = this.$attrs[key]
           return obj
         }, {})
     }
   }
}
</script>

Leave a comment