版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31490071/article/details/87808949
最近由于项目需要,需要实现一个带图标的input框,但一直没有找到一个很好的方法,所以只能自己动手写了。
该控件是单独写的,所以可以拿来直接使用。
先说一下该控件支持的功能:
1.从外部动态传入placeholder的值
2.从外部传入图标地址并给图标增加点击事件
3.外部监听input的change事件并获取input的输入值,input禁止输入表情元素和特殊字符
4.外部可动态设置input的值
5.支持input内容本地存储和读取,可选择是否开启本地存储
实现效果:
下面直接上实现代码inputwithicon.vue:
<template>
<!--右侧带图标的输入框,长度限制为40个字符,禁止输入表情和某一些特殊元素 -->
<div class="input_co_type">
<input type="text" :placeholder="inputOtion.placeholdertxt" v-model="inputvalue" class="input_type" maxlength="40" @change="changeEvent"/>
<div class="inputicon" @click="clearvalue">
<img :src="inputOtion.iconurl" >
</div>
</div>
</template>
<script>
export default {
name: "",
data() {
return {
inputvalue:''
}
},
props:{
inputOtion:{
type:Object,
default:{
placeholdertxt:"说点什么吧",
iconurl:'', //图标地址
autostorage:false, //是否自动缓存,该值设置为true时必须设置storagename的值
storagename:'' //缓存变量存储的变量名称
}
},
},
mounted:function(){
if(this.inputOtion.autostorage){
this.inputvalue =window.localStorage.getItem(this.inputOtion.storagename);
}
},
methods: {
clearvalue(){
this.inputvalue='';
if(this.inputOtion.autostorage){
window.localStorage.setItem(this.inputOtion.storagename,this.inputvalue);
}
},
changeEvent(){
this.$emit('changeEvent',this.inputvalue);
if(this.inputOtion.autostorage){
window.localStorage.setItem(this.inputOtion.storagename,this.inputvalue);
}
},
changeValue:function(value){
this.inputvalue =value;
}
},
watch:{
inputvalue:function(val){
this.inputvalue = val.replace(/[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!,。?!…—&$=()-+/*{}[\]]|\s/g, '')
}
},
}
</script>
<style scoped>
.input_co_type{
width:100%;
height:48px;
background: white;
margin-top: 10px;
display: flex;
}
.input_type{
height:48px;
border: none;
font-size: 14px;
color: #333333;
letter-spacing: 0;
padding-left:16px;
flex:1;
outline: none;
}
.inputicon{
width:40px;
height:48px;
margin-left:15px;
}
.inputicon>img{
position:relative;
width:16px;
height:16px;
padding-top:16px;
padding-right:16px;
}
</style>
调用方法和代码:
<template>
<div class="xxx">
<input-icon :inputOtion="Option" @changeEvent="changeValue" ref="changeinput"></input-icon>
</div>
</template>
<script>
import InputWithIcon from './inputwithicon.vue'
import delIcon from '../../../assets/mine/bottom_del.png'
export default {
name: "",
data() {
return {
Option:{
placeholdertxt:'说点什么吧',
iconurl:inputDelIcon,
autostorage:false,
storagename:'storagename'
},
inputValue :''
},
methods: {
changeValue(val){
this.inputValue = val;
}
},
components:{
'input-icon':InputWithIcon
}
}
</script>
<style scoped>
</style>
这里涉及到三个知识点:
1.父元素调用子元素中的方法
2.子元素调用父元素中的方法
3.父元素给子元素传值
4.子元素给父元素传值
具体实现方法请参考其他博客内容