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
<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.
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
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