封装成组件
子组件
<template>
<div>
<el-form ref="form" label-width="100px">
<el-form-item :label="label">
<div id="qwe">
<el-select
v-model="_value"
:clearable="true"
placeholder="请选择"
:style="selectCss"
ref="selectblur"
>
<el-option value="无" style="height: auto">
<el-tree
:data="data"
node-key="id"
:accordion="false"
:props="defaultProps"
@node-click="handleNodeClick"
></el-tree>
</el-option>
</el-select>
</div>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: "selectTree",
props: ["data", "defaultProps", "value","label","selectCss"],//[树,'','',显示的标签,输入框的长度]
computed: {//计算属性,子组件不能直接更改父组件的值,可以通过计算属性显示
_value: {
get() {
return this.value;
},
set(val) {
//this._value=val
}
}
},
methods: {
handleNodeClick(data) {
//树形选择
if (data.children === undefined) {
this._value = data.label;
this.$emit("SelectNode", data.label, data); //父组件定义 @SelectNode='父组件接受参数'。 子组件传递数据给父组件
this.$refs.selectblur.blur(); //ref 相当于dom选择器,$refs选取,blur()取消焦点
}
}
}
};
</script>
<style>
.qwe {
margin-left: 200px;
}
</style>
父组件
调用
<selectTree
:data="data"
:defaultProps="defaultProps"
:value="value"
:label="'选择产品'"
:selectCss="' 500px;'"
@SelectNode="ChangeselectTree"
></selectTree>
接受传递的值
ChangeselectTree(val, data) {
this.value = val;
// console.log("父组件")
console.log(data)
}
测试组件
<template>
<div>
<el-select v-model="value" :clearable="true" placeholder="请选择">
<el-option value="无" style="height: auto">
<el-tree :data="data" node-key="id" :accordion="true" @node-click="handleNodeClick"></el-tree>
</el-option>
</el-select>
</div>
</template>
<script>
export default {
data() {
return {
data: [
{
label: "一级 1",
children: [
{
label: "二级 1-1",
children: [
{
label: "三级 1-1-1"
}
]
}
]
},
{
label: "一级 2",
children: [
{
label: "二级 2-1",
children: [
{
label: "三级 2-1-1"
}
]
},
{
label: "二级 2-2",
children: [
{
label: "三级 2-2-1"
}
]
}
]
},
{
label: "一级 3",
children: [
{
label: "二级 3-1",
children: [
{
label: "三级 3-1-1"
}
]
},
{
label: "二级 3-2",
children: [
{
label: "三级 3-2-1"
}
]
}
]
}
],
defaultProps: {
children: "children",
label: "label"
},
value: ""
};
},
methods: {
handleNodeClick(data) {
//树形选择
this.value = data.label;
}
}
};
</script>