javascript - 为什么我在 Vue 中的移动标签效果不起作用?
问题描述
嘿伙计们,我试图在 vue 中重新创建这样的效果:
正如您所看到的,当用户开始在输入框中输入时,标签会移动并显示出来。
但是,我正在努力访问输入框中的值以检查它们是否为空。
这是我的Vue模板:
<template>
<div class="desktop-landing-search">
<!---------------------------------------JOB SEARCH WRAPPER--------------------------------------->
<div class="desktop-landing-search__search-wrapper">
<div class="desktop-landing-search__input-box">
<label for="inputType" ref="typeLabel">Graduate or Internship</label>
<input
type="text"
class="desktop-landing-search__input-box__input-search"
id="inputType"
placeholder="Graduate or Internship"
ref="inputJobType"
v-on:input="showLabel('type')"
/>
</div>
<div class="desktop-landing-search__input-box">
<label for="inputIndustry" ref="industryLabel">Industry</label>
<input
type="text"
class="desktop-landing-search__input-box__input-search"
id="inputIndustry"
placeholder="Industry"
ref="inputIndustry"
/>
</div>
<div class="desktop-landing-search__input-box">
<label for="inputLocation" ref="locationLabel">Location</label>
<input
type="text"
class="desktop-landing-search__input-box__input-search"
id="inputLocation"
placeholder="Location"
ref="inputLocation"
/>
</div>
<div class="desktop-landing-search__input-box">
<button class="desktop-landing-search__btn-search">Search</button>
</div>
</div>
</template>
这是我用来显示标签的方法:
<script>
export default {
name: "DesktopLandingSearch",
methods: {
showLabel: function(input) {
if (this.input === "type" && this.refs.inputJobType.value != "") {
this.refs.typeLabel.classList.toggle("show-label");
window.alert("testing job type");
}
if (this.input === "industry" && this.refs.inputIndustry.value != "") {
this.refs.industryLabel.classList.toggle("show-label");
window.alert("test job industry");
}
if (this.input === "location" && this.refs.inputLocation.value != "") {
this.refs.locationLabel.classList.toggle("show-label");
window.alert("test job location");
}
}
}
};
</script>
这是我要切换的课程:
.show-label {
top: -130%;
opacity: 1;
}
谁能告诉我我做错了什么?
解决方案
你调查过v-model
吗?
如果您v-model="inputIndustry"
输入该输入,则在您的方法上方输入:
data() {
return {
inputIndustry: ""
}
}
在输入中键入的任何内容都会插入或“绑定”到inputIndustry
数据属性。
因此,showLabel
您可以检查是否this.inputIndustry !== ""
,然后做任何您喜欢的事情。
如果删除对input
参数的所有引用并将它们替换为对绑定数据属性的引用,则可以直接访问输入值。您还需要@keydown="showLabel"
输入每个输入,以便触发该方法。
如果您需要,文档是一个很好的帮助:https ://vuejs.org/v2/guide/forms.html
v-bind
如果您想切换类,请查看类绑定: https ://vuejs.org/v2/guide/class-and-style.html#Object-Syntax