I wrote a mounted function to conditionally add and remove classes from an element in a Vuejs component. It appears that the function adds the class to the element in not only this instance of the component but in all instances of that component. Why is this? Do I need to be using refs? The greater context is a form. Each instance of this component is a form field with a floating label. The reason for adding and removing the class is to create the floating label.
It also appears that the mutableFieldContent === '' is never true even the mutableFieldContent is empty/undefined. Not sure why this is the case either.
I'm kind of new to Stack Overflow. I apologize if this should be two questions.
Thanks!
<template>
<div class="form-field" id="outerdiv">
<div class="form-field__control">
<label for="exampleField" class="form-field__label">{{fieldLabel}}</label>
<input id="exampleField" v-model="mutableFieldContent" @blur="setActive(false, $event)" @focus="setActive(true, $event)"
type="text" class="form-field__input" />
</div>
</div>
</template>
<script>
import $ from "jquery";
export default {
name: "FormField",
props: {fieldContent: String, fieldLabel: String},
data() {
return {
mutableFieldContent: this.fieldContent
}
},
methods: {
setActive(active, event) {
const formField = event.target.parentNode.parentNode
if (active) {
formField.classList.add('form-field--is-active')
} else {
formField.classList.remove('form-field--is-active')
event.target.value === '' ?
formField.classList.remove('form-field--is-filled') :
formField.classList.add('form-field--is-filled')
}
}
},
mounted() {
console.log("this.mutableFieldContent: "+this.mutableFieldContent);
console.log("classList of element: "+ $("#outerdiv")[0].classList);
this.mutableFieldContent === ""?
(console.log("fieldContent is empty"),
$("#outerdiv")[0].classList.remove('form-field--is-filled')):
(console.log("fieldContent exists"),
($("#outerdiv")[0].classList.add('form-field--is-filled')))
}
}
</script>
<style>
.form-control{
border-style: none;
width: 100%;
height: 34px;
padding: 0px 0px;
font-size: 20px;
background: none;
text-decoration-line: underline;
}
</style>
And here is where I insert the component...
<div v-for="field in category.fields" v-bind:key="field.label">
<div class="row">
<div class="col">
<div v-if="!field.haschoices">
<FormField
:fieldContent="person[field.personfield]"
:fieldLabel="field.label"
></FormField>
</div>