子组件代码
<template> <div class="input-group" id="inputgroup"> <input :type="type" :placeholder="placeholder" :class="classname" :value="currentValue" :readonly="readonly" :style="inputstyle" @input="handleInput"/><!--input 事件在输入框内容改变的时候触发--> <span class="input-group-btn input-btn-close" v-if="currentValue?true:false" @click="clear"><!--在currentValue有值的情况下出现--> <button class="btn" type="button">×</button> </span> </div> </template>
export default {
name: 'inputgroup',
props:{
type: {
type: String,
default: 'text'
},
value:{},
placeholder: String,
readonly: Boolean,
classname:{},//取名classname而不是class,因为class会出现语义不明产生bug
inputstyle:{} //取名inputstyle而不是style,因为style会直接执行在父组件上
},
data() {
return {
currentValue: this.value
};
},
methods:{
clear:function () {
this.currentValue ='';
},
handleInput(evt) {
this.currentValue = evt.target.value; //currentValue赋值为 输入框的值
}
},
watch: { //监听value和currentValue的值
value(val) {
this.currentValue = val;
},
currentValue(val) { //当currentValue改变的时候 触发事件 将val发射给input
this.$emit('input', val);
},
}
}
父组件调用 方法
<input-item placeholder="输入订单金额" classname="no-border text-right" type="text" readonly v-model="cash" inputstyle="padding-right: 5px;"></input-item>
有不足和误解的地方 请大神们多多指教
浙公网安备 33010602011771号