封装的下拉选项框
<template>
<el-select v-model="value" filterable :placeholder="'请选择'+select.name" @change="changeValue">
<el-option
v-for="item in select.data"
:key="item.value"
:label="item.label"
:value="item.value"
>
</el-option>
</el-select>
</template>
<script>
export default {
name: "Select",
props: {
select: Object
},
computed: {
//将value的值通过computed的方式进行动态监控
value: {
get() {
//解决有默认值时,子下拉菜单未显示菜单的问题
this.select.result && this.changeValue(this.select.result)
return this.select.result
}, set() {
}
}
},
data() {
return {
// value: this.select.result//设置了默认值
}
},
created() {
},
methods: {
changeValue(value) {
//当下拉选项框的值改变的时候,获取最新的值
this.select.result = value;
//change有的时候才执行
this.select.change && this.select.change(this.buildChildren(value))
},
buildChildren(val) {
const date = this.select.data.find(item => {
return item.value == val
})
//返回一级下拉选项框的子选项
return date.children;
}
}
}
</script>
对封装的下拉选项框的使用
<template>
<div class="SelectMain">
<Select :select="select"/>
<Select :select="selectChild"/>
</div>
</template>
<script>
import Select from "@/components/selectTest/Select";
export default {
name: "SelectMain",
components: {
Select
},
data() {
return {
//下拉选项框需要传递的参数
select: {
result: "选项1",//用于接收选择值,并设置默认值
name: "食物",//提示语
change: (childDate) => {
console.log(childDate);
//当一级下拉框的值改变的时候,清空子选项的值
this.selectChild.result="";
this.selectChild.data = childDate;
},
data: [{
value: '选项1',
label: '黄金糕',
children: [{
value: '选项1-1',
label: '黄金糕1-1',
}, {
value: '选项1-2',
label: '黄金糕1-2',
}]
}, {
value: '选项2',
label: '双皮奶',
children: [{
value: '选项2-1',
label: '双皮奶2-1',
}, {
value: '选项2-2',
label: '双皮奶2-2',
}]
}, {
value: '选项3',
label: '蚵仔煎',
children: [{
value: '选项3-1',
label: '蚵仔煎3-1',
}, {
value: '选项3-2',
label: '蚵仔煎3-2',
}]
}, {
value: '选项4',
label: '龙须面'
}, {
value: '选项5',
label: '北京烤鸭'
}]
},
selectChild: {
result: "",//用于接收选择值,并设置默认值
name: "食物子菜单",//提示语
data: []
}
}
}
}
</script>
效果展示: