Search.vue组件 主要做的事情是:
1.用户输入内容的时候,出现右侧“x”关闭图标
2. 右侧“x”关闭图标,的作用:就是点击它,可以清空文本框中的内容
3.文本框内容,输入的内容,设置上限,最多允许输入内容 不超过20个字。
4.文本框的外形---是方形,还是圆形?
通过 给自己 添加 自定义属性props~~~ shape
5.父组件app.vue,传入数据
传入 round,显示是圆
<search shape="round"></search>
传入square,显示是方形
<search shape="square"></search>
html:
<template>
<div class="search-body">
<!-- 搜索输入框 -->
<div class="search-input-body">
<input type="text" v-model="kw" class="search-input-el" :style="{borderRadius:rarius}">
<span class="clear-btn" @click="clearKw" v-show="kw.length>0">x</span>
</div>
</div>
</template>
css:
<style scoped>
.search-body{
display: flex;
}
/* 包裹input和x按钮的div盒子 */
.search-input-body{
width: 200px;
height: 30px;
line-height: 30px;
position: relative;
margin-right: 10px;
}
.search-input-el{
width: 200px;
height: 30px;
border: 0;
outline: none;
background: #eee;
}
.clear-btn{
position: absolute;
top: 0;
right: 10px;
cursor: pointer;
}
</style>
js:
<script>
export default {
// 自定义2个属性,用于父组件在使用这个组件的时候,向这个组件里传值
// 这2个属性的数据类型设置如下
props:{
shape:{
type:String,
default:'square',
validator:function(val){
return ['square','round'].includes(val)
}
},
clearable:{
type:Boolean,
default:true
}
},
data() {
return {
// 搜索关键字
kw:''
}
},
watch:{
// 数据监听kw里的值,不允许用户输入超过20个字符
kw(val,oldVal){
if(val.length>20){
this.kw = oldVal
}
}
},
computed:{
// rarius依赖于响应式数据(shape)的,rarius这个值,是通过一系列运算得到。
rarius(){
let val;
if(this.shape == 'round'){
val = '20px';
}else{
val = '0px';
}
return val
}
},
methods: {
clearKw(){
this.kw = ''
}
},
};
</script>