我正在尝试向Vuejs中的元素添加和删除类。我的代码中缺少的链接是classList返回undefined。为什么是这样?谢谢。我正在用jQuery getElementById速记$
来抓取元素<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="fieldContent" @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},
methods: {
setActive(active, event) {
console.log("this.fieldContent: "+this.fieldContent);
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')
}
}
},
updated() {
console.log("in initialize form field");
console.log("this.fieldContent: "+this.fieldContent);
console.log("result from shorthand getElementById: "+$("#outerdiv"));
console.log("classList of element: "+ $("#outerdiv").classList);
this.fieldContent === '' ?
$("#outerdiv").classList.remove('form-field--is-filled'):
$("#outerdiv").classList.add('form-field--is-filled')
}
}
</script>
<style>
.form-control{
border-style: none;
width: 100%;
height: 34px;
padding: 0px 0px;
font-size: 20px;
}
</style>
答案 0 :(得分:0)
在解决了主要问题后,您可以简化代码,同时通过Vue方式消除对jQuery的需求。
通过使用class bindings,您可以将ifs替换为计算的prop,如果需要直接访问元素,则可以使用refs。
只需运行以下代码片段,即可了解这些概念的实际作用:
new Vue({
el: '#app',
data: {
fieldContent: '',
fieldLabel: '',
active: false,
},
computed: {
classList() {
return {
'form-field--is-filled': this.fieldContent !== '',
'form-field--is-active': this.active,
};
}
},
methods: {
setActive(active, event) {
console.log("this.fieldContent: "+this.fieldContent);
this.active = active;
}
},
updated() {
console.log("in initialize form field");
console.log("this.fieldContent: "+this.fieldContent);
console.log("result from shorthand getElementById: ", this.$refs.outerDiv);
console.log("classList of element: "+ this.$refs.outerDiv.classList);
}
});
.form-control{
border-style: none;
width: 100%;
height: 34px;
padding: 0px 0px;
font-size: 20px;
}
.form-field--is-active {
border: 1px solid green;
}
.form-field--is-filled {
outline: 1px dotted blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="form-field" id="outerdiv" :class="classList" ref="outerDiv">
<div class="form-field__control">
<label for="exampleField" class="form-field__label">{{fieldLabel}}</label>
<input id="exampleField" v-model="fieldContent" @blur="setActive(false, $event)" @focus="setActive(true, $event)"
type="text" class="form-field__input" />
</div>
</div>
</div>