正文之前,先吐槽一下现在网上技术文章的现状,用几个字概括就是:抄来抄去。对学习技术和交流技术的伙伴很不友好,看的人甚是不爽和糟心。
好了,进入正文。
最近博主最近在学习vue准备给公司做一个简单的网站,于是使用了vue+elementui,后端使用的java。
其中的留言功能有输入框,就想实现一个正常的判空功能,如果在输入框未输入文字或者输入了文字然后删除了,输入框会变红;如果有文字输入则恢复正常,起到一个实时变化的效果。
其中:class用来动态产生class;v-on监听输入框的变化。
为方便理解已删除了部分代码,如下:
<template>
<div>
<el-row>
<el-col :span="12" :offset="1">
<div class="messageborder">
<el-row class="messagerow">
<el-col :span="3" class="messagecol">
<span class="content">name:</span>
</el-col>
<el-col :span="7" class="messagecol">
<input v-model="firstname" :class="{messageinput : firstnamecheck}" v-on:input="namecheck"></input>
</el-col>
<el-col :span="6" v-show="namewarning">
<span class="warningmessage">Name cannot be empty</span>
</el-col>
</el-row>
<el-row class="messagerow">
<el-col :offset="3" class="messagecol">
<el-button type="primary" size="small" @click="submit()">submit</el-button>
</el-col>
</el-row>
</div>
</el-col>
</el-row>
<router-view></router-view>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
firstname:'',
firstnamecheck:false,
phonecheck:false,
phonewarning:false,
namewarning:false
}
},methods:{
namecheck(){
if(this.firstname.length==0){
this.firstnamecheck=true;
this.namewarning=true;
}else{
this.firstnamecheck=false;
this.namewarning=false;
}
}
},
submit(){
var that = this;
if(that.firstname=='' || that.firstname==null){
that.firstnamecheck=true;
that.namewarning=true;
return false;
}
axios({
url: "http://localhost:8082/message/customerMessage",
method: 'post',
params:{
firstname:that.firstname,
titleexplain:that.titleexplain,
title:that.title,
phone:that.phone
}
})
.then(function (response) {
that.firstname='',
that.titleexplain='',
that.title='',
that.phone=''
that.$message({
type: 'success',
message: '留言成功!'
});
}).catch(function (reason) {
});
},
}
}
</script>
<style scoped>
.messageinput{
border-color: red;
}
.warningmessage{
font-size: 12px;
color: red;
}
</style>
不考虑引入jq使用dom的情况下:
至于博主为什么不用el-input,因为el-input的控制样式的在封装的标签里面,如需修改样式,需要用到深度选择器/deep/。
如图
但是这样的话,就无法使用v-bind动态绑定class,因为你的:class无法加到封装的input上。暂未想到什么简单的解决办法,如果有大佬有解决办法,也在此虚心请教。
最后放上效果图:
直接点击提交输入文字之后
再次删除,效果如第一张图。