一、介绍
针对element-ui的el-input组件进行封装,需要添加element-ui的依赖
二、FirstCustomWrapInput组件
<template>
<div>
<el-input
v-model="value"
@input="$emit('input', value)"
@blur="$emit('blur1')"
@focus="$emit('focus1')"
></el-input>
</div>
</template>
<script>
export default {
name: "FirstCustomWrapInput",
model: {
prop: "initValue",
event: "input",
},
props: ["initValue"],
data() {
return {
value: this.initValue,
};
},
watch:{
initValue(newValue){
this.value = newValue
}
}
};
</script>
<style scoped>
.el-input {
padding: 20px;
}
.el-input >>> .el-input__inner {
background: #bfa;
border-top: none;
border-left: none;
border-right: none;
}
</style>
三、SecondCustomWrapInput组件
<template>
<div>
<!-- 这种使用方式会要求,父组件传递的$listeners里面的属性名称
是所封装组件能触发的。否则无效 -->
<el-input v-bind="$attrs" v-on="$listeners"></el-input>
</div>
</template>
<script>
export default {
name: "SecondCustomWrapInput",
};
</script>
<style scoped>
.el-input {
padding: 20px;
}
.el-input >>> .el-input__inner {
background: #bfa;
border-top: none;
border-left: none;
border-right: none;
}
</style>
四、App组件
<template>
<div id="app">
<h3>方式一</h3>
<first-custom-wrap-input
v-model="value"
@blur1="handleBlur"
@focus1="handleFocus"
></first-custom-wrap-input>
<hr/>
<h3>方式二</h3>
<second-custom-wrap-input
v-model="value"
@blur="handleBlur"
@focus="handleFocus"
></second-custom-wrap-input>
value当前值:{{ value }}
<hr/>
<h3>element-ui组件</h3>
<el-input v-model="value"/>
<button @click="value='国货之光'">点我</button>
</div>
</template>
<script>
import FirstCustomWrapInput from "./components/FirstCustomWrapInput.vue";
import SecondCustomWrapInput from "./components/SecondCustomWrapInput.vue";
export default {
name: "App",
components: { FirstCustomWrapInput,SecondCustomWrapInput },
data() {
return {
value: "333",
};
},
methods: {
handleBlur() {
console.log("blur");
},
handleFocus() {
console.log("focus");
},
},
};
</script>
<style scoped>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
padding: 100px;
}
</style>
四、效果图