Last active
February 17, 2025 13:40
-
-
Save atomjoy/e70113fb5a9aaf69a23e15820c8575a0 to your computer and use it in GitHub Desktop.
How to catch class attributes in vue 3 components.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { useAttrs, ref } from 'vue'; | |
const emits = defineEmits(['update:modelValue', 'valid', 'invalid']); | |
const props = defineProps({ | |
modelValue: [String, Number], | |
name: { type: String }, | |
label: { type: String }, | |
placeholder: { type: String }, | |
type: { type: String, default: 'text' }, | |
focus: false, | |
}); | |
// Disable attrs inherit | |
// Catch class in defineProps({ class: { type: String } }) | |
// or use | |
defineOptions({ | |
// Disable attrs inherit for first element | |
// then use :class="$attrs.class" | |
// or v-bind="$attrs" in inner element | |
inheritAttrs: false, | |
}); | |
const attrs = useAttrs(); | |
let open = ref(false); | |
console.log('Attr', attrs); | |
function onFocus(event) { | |
open.value = true; | |
validatePass(event); | |
} | |
function onBlur(event) { | |
open.value = false; | |
} | |
function validatePass(event) { | |
let str = event?.target?.value ?? ''; | |
if (str.replace(' ', '').length >= 3) { | |
emits('valid', str); | |
} else { | |
emits('invalid', str); | |
} | |
} | |
</script> | |
<template> | |
<div class="form-group"> | |
<label class="form-label">{{ props.label }}</label> | |
<input | |
v-model="props.modelValue" | |
class="form-input" | |
:class="$attrs.class" | |
:type="props.type" | |
:name="props.name" | |
:placeholder="props.placeholder" | |
@input="emits('update:modelValue', $event.target.value)" | |
@keyup="validatePass" | |
@focus="onFocus" | |
@blur="onBlur" | |
/> | |
</div> | |
</template> | |
<!-- https://vuejs.org/guide/components/attrs --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import InputAttrs from '@/components/InputAttrs.vue' | |
<template> | |
<InputAttrs class="input-class-only" /> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment