随着前端开发的日益组件化,前端应用的开发也逐渐成为组件化开发。文本以Element UI为框架,实现一个简单可复用的范围输入组件。
1.组件引入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| <template> <div class="box"> <rangeInput style="width: 300px;" size="small" start-placeholder="开始范围" end-placeholder="止支付总额" separator="至" type="number" @handleRangeValue="getRangeValue" > </rangeInput> </div> </template>
<script> import Vue from 'vue'
import rangeInput from './range'
export default { data() { return { } }, mounted(){ }, methods: { getRangeValue(startVal, endVal){ console.log(startVal, endVal, 'range value') }, }, components: { rangeInput } }
</script>
|
2.编写组件range.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| <template> <div class="ri-wrap"> <el-col :span="11"> <el-input class="ri-input" :size="size" :placeholder="startPlaceholder" @change="changeValueRange" v-model="startRange" :type="type" > </el-input> </el-col> <el-col :span="2"> <span style="line-height: 36px;font-size: 14px;padding: 0 5px">{{separator}}</span> </el-col> <el-col :span="11"> <el-input class="ri-input" :size="size" :placeholder="endPlaceholder" @change="changeValueRange" v-model="endRange" :type="type" > </el-input> </el-col> </div> </template>
<script> export default { data() { return { startRange: '', endRange: '', type: 'text', } }, props: { size: String, startPlaceholder: String, endPlaceholder: String, separator: String, }, mounted() { }, methods: { changeValueRange(){ let startRange = this.startRange || 0; let endRange = this.endRange || 0; this.$emit('handleRangeValue', startRange, endRange) }, } } </script>
<style> .ri-wrap{ border-radius: 4px; border: 1px solid #dcdfe6; height: 36px; line-height: 36px; box-sizing: border-box; } .ri-input .el-input__inner{ border: none !important; font-size: 14px; } </style>
|
组件内通过@change
监听input
输入的值,通过$emit
向父级派发事件handleRangeValue
,传递对应的参数,然后在父级监听派发的事件,获取到对应的值。本案例只是一个简单的子向父通信的案例,其实还可以继续扩展,比如:范围校验,样式自定义等等。