vue之封装选择下拉树

这篇博客展示了如何利用ElementUI的el-select和el-tree组件创建一个下拉选择树的功能。通过设置节点点击事件和属性,实现了选中节点后将节点信息转换为选中值,并提供了清空选项的功能。代码示例详细说明了组件的使用方法和数据绑定过程。

最近在做项目的过程中,用到下拉选择树的效果,主要用elementUI的

el-select与el-tree,直接上代码
<template>
    <div class="box">
        <el-select size="small" v-model="value" multiple placeholder="请选择" clearable @clear="selectClear"  collapse-tags>
            <el-option class="option-style" :value="selectTree">
                <el-tree ref="tree" :data="list" :props="defaultProps"
                         node-key="id" show-checkbox @check-change="handleNodeClick">
                    <div slot-scope="{node, data}">
                        <span :class="[{'tree-click': treeClick==data.value}]">{{data.label}}</span>
                    </div>
                </el-tree>
            </el-option>
        </el-select>
    </div>
</template>

<script>
  export default {
    data() {
      return {
        treeClick:null,
        value:[],
        selectTree:[],
      }
    },
    props: {
      list: {
        type: Array,
        default: () => []
      },
      defaultProps: {
        type: Object,
        default: () => {}
      }
    },
    methods: {
      handleNodeClick(data,self,child) {
        console.log(this.$refs.tree.getCheckedNodes())
        let datalist = this.$refs.tree.getCheckedNodes()
        this.selectTree = [] //置空
        this.value = []
        datalist.forEach((item)=>{
          this.selectTree.push({id:item.id,label:item.label})
          this.value.push(item.label)
        })
      },
      selectClear() {
        this.value = [];
        this.selectTree = [];
        this.$refs.tree.setCheckedKeys([]);//清空树选中状态
      },
    },
  }
</script>

<style scoped>
    .box {
        width: 100%;
        height: 100%;
    }

    .option-style {
        padding: 0;
        width: 100%;
        height: 100%;
        background-color: #FFFFFF;
    }
    /deep/ .el-select .el-input--small .el-input__inner{
        height: 28px;
        line-height: 28px;
    }
    /deep/ .el-select .el-input--small .el-input__icon {
        line-height: 28px;
    }
</style>

应用:

 <selectTree :defaultProps="defaultProps" :list="list"></selectTree>

js部分

<script>
    import selectTree from './select-tree'
export default {
  name: 'page1',
  components: {
    selectTree
  },
  data() {
    return {
      defaultProps:{
        children: 'children',
        label: 'label'
      },
      list: [{
        id: 1,
        label: '一级 2',
        children: [{
          id: 3,
          label: '二级 2-1',
          children: [{
            id: 4,
            label: '三级 3-1-1'
          }, {
            id: 5,
            label: '三级 3-1-2',
          }]
        }, {
          id: 2,
          label: '二级 2-2',
          children: [{
            id: 6,
            label: '三级 3-2-1'
          }, {
            id: 7,
            label: '三级 3-2-2',
          }]
        }]
      }],
    }
  },
  methods: {}
}
</script>

### 封装 Vue2 下拉组件示例教程 在 Vue2 中封装一个下拉组件需要考虑以下几个方面:组件的结构设计、父组件与子组件之间的数据传递以及事件通信机制。以下是一个完整的封装示例,包含组件的开发和使用方法。 #### 1. 子组件开发 首先创建一个名为 `SelectComponent.vue` 的文件,用于封装下拉组件的逻辑和模板。 ```vue <template> <div class="select-container"> <div class="select-header" @click="toggleOptions"> {{ selectedValue || placeholder }} <span class="arrow-icon">▼</span> </div> <ul v-if="showOptions" class="select-options"> <li v-for="(option, index) in options" :key="index" @click="selectOption(option)" :class="{ 'selected-option': option === selectedValue }" > {{ option }} </li> </ul> </div> </template> <script> export default { name: "SelectComponent", props: { options: { type: Array, required: true, }, placeholder: { type: String, default: "请选择", }, }, data() { return { showOptions: false, selectedValue: null, }; }, methods: { toggleOptions() { this.showOptions = !this.showOptions; }, selectOption(option) { this.selectedValue = option; this.$emit("input", option); // 使用 v-model 双向绑定 this.showOptions = false; }, }, }; </script> <style scoped> .select-container { position: relative; width: 200px; } .select-header { padding: 8px; border: 1px solid #ccc; cursor: pointer; display: flex; justify-content: space-between; align-items: center; } .select-header:hover { background-color: #f0f0f0; } .select-options { position: absolute; top: 100%; left: 0; width: 100%; border: 1px solid #ccc; max-height: 150px; overflow-y: auto; background-color: white; z-index: 10; } .select-options li { padding: 8px; cursor: pointer; } .select-options li:hover { background-color: #f0f0f0; } .selected-option { font-weight: bold; } </style> ``` #### 2. 父组件中使用 接下来,在父组件中引入并使用这个封装好的下拉组件。 ```vue <template> <div> <h3>性别选择</h3> <SelectComponent :options="genderOptions" v-model="selectedGender" placeholder="请选择性别" /> <p>当前选择的性别是:{{ selectedGender }}</p> </div> </template> <script> import SelectComponent from "./components/SelectComponent"; export default { components: { SelectComponent, }, data() { return { genderOptions: ["男", "女"], selectedGender: "", }; }, }; </script> ``` #### 3. 打包为库 如果需要将此组件打包为库供其他项目使用,可以按照以下步骤操作: - 将所有组件放入一个文件夹(如 `package`)。 - 创建 `index.js` 文件,引入所有组件并声明 `install` 方法。 ```javascript // index.js import SelectComponent from './SelectComponent'; const components = [SelectComponent]; const install = (Vue) => { components.forEach((component) => { Vue.component(component.name, component); }); }; if (typeof window !== 'undefined' && window.Vue) { install(window.Vue); } export default { install }; ``` 通过以上步骤,可以实现一个功能完善的 Vue2 下拉组件,并将其封装为可复用的库[^1]。 #### 注意事项 - 在子组件中,通过 `props` 接收父组件传递的数据[^2]。 - 使用 `$emit` 方法将子组件的选择结果传递给父组件[^3]。 - 如果需要支持 `v-model`,可以在子组件中通过 `input` 事件实现双向绑定[^1]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值