仿写elementui------select下拉框讲解
1.父组件
<mia-form-item label="美食"> <mia-select v-model="food" :data="options" placeholder="请选择美食"> <mia-option label="区域一" value="shanghai"></mia-option> <mia-option label="区域二" value="beijing"></mia-option> </mia-select> </mia-form-item>
2.select组件(slot盛放option的代码)
<template> <div class="mia-select"> <div class="mia-input" @click="unfoldDrop"> <input type="text" class="mia-input-inner" :placeholder="placeholder" v-model="anser.label" readonly> <i class="iconfont mia-drop-btn" :class="{unfold:unfold}">{{canOpenDrop ? '' : ''}}</i> <div class="mia-select-dropList" v-show="unfold"> <mia-scroll height="274px"> <ul> <slot></slot> </ul> </mia-scroll> </div> </div> <!-- msg:{{msg}} --> </div> </template>
3.option组件
<template> <li @click="chooseSelect">{{label}}</li> </template>
4.问题来了:option组件通过$emit只能跟父组件传值,但是父组件里并没有定义事件进行接受,那么我们如何将option的值传给select呢?
解决:
我们知道option父组件为select,可通过遍历其子集加事件绑定接受数据:
1)在select里添加(不知如何找子集的可以打印this.$children进行查看):
getSelect(msg){ console.log('接收',msg); var obj={...msg}; this.anser=obj; this.$emit("input",obj.value); } }, mounted(){ this.$children[0].$children.forEach(child => child.$on('chooseValue',this.getSelect)) },
2.在option里头添加
chooseSelect(){ var label=this.label,value=this.value; console.log('发射'); this.$emit("chooseValue",{label,value}); }