Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue 3: excluding fallthrough attributes from attrs

I’m working on a custom input component which has a parent div and a label. I’d like to apply any classes to the parent div but I also want to make sure that any other fallthrough attributes get applied to the input component.

Here’s a simplified version of my component

In App.vue

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script setup>
import { ref } from 'vue'
import MyInput from './MyInput.vue'

const msg = ref('I only want the outer blue box')
</script>

<template>
  <h1>{{ msg }}</h1>
  <my-input class="blue" aria-foo="foo" aria-bar="bar"/>
</template>

<style>
  .blue {
    padding: 1rem;
    border: 3px solid blue;
  }
</style>

In MyInput.vue

<template>
  <div :class="attrs.class">
    <input v-bind="attrs" >
  </div>
</template>

<script>
export default {
  inheritAttrs: false,
  customOptions: {}
}
</script>

<script setup>
 import { useAttrs, computed } from 'vue'
 const attrs = useAttrs();
</script>

Is there a good way to get all the attrs except for the class? I tried making a copy of attrs using a computed but that didn’t seem to work.

This is what I tried:

const inputAttrs = computed(()=>{
  let returnObj = {}
  for (attr in attrs) {
    if (attr !== 'class') {
      returnObj[attr] = attrs[attr]
    }
  }
  return returnObj;
})

Apparently attr in the for loop was not defined? Essentially I want the input to get the aria-foo and aria-bar attributes without the class property.

Here’s a Link to the SFC Playground with the above code.

>Solution :

The error says that attr was not defined as you need to define it within the for() using the for…in syntax.

const inputAttrs = computed(()=>{
  let returnObj = {}
  // use const below
  for (const attr in attrs) {
    if (attr !== 'class') {
      returnObj[attr] = attrs[attr]
    }
  }
  return returnObj;
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…in

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading