el-tree 和 el-switch 組合使用
阿新 • • 發佈:2022-03-03
1、效果
2、元件程式碼
<template> <div style="width: 300px"> <div> <el-input placeholder="輸入關鍵字進行過濾" v-model="filterText" >></el-input > </div> <el-tree :data="treeData" :props="defaultProps" :width="treeWith" @node-click="handleNodeClick" node-key="id" :expand-on-click-node="false" :filter-node-method="filterNode" default-expand-all ref="mapTree" > <span class="custom-tree-node" slot-scope="{ data }"> <span>{{ data.label }}</span> <span> <el-switchv-model="data.isChecked" active-color="#13ce66" inactive-color="#ff4949" :width="35" :active-value="true" :inactive-value="false" @change="switchOpenOrClose(data)" > </el-switch> </span> </span> </el-tree> </div> </template> <script> exportdefault { name: "SwitchTree", props: { treeData: { type: Array, }, treeWith: { type: Number, default: 200, }, }, data() { return { filterText: "", defaultProps: { children: "children", label: "label", }, }; }, methods: { handleNodeClick() {}, switchOpenOrClose(data) { this.$emit("openswitch", data); }, filterNode(value, data) { if (!value) return true; return data.label.indexOf(value) !== -1; }, }, watch: { filterText(val) { this.$refs.mapTree.filter(val); }, }, }; </script> <style scoped> .custom-tree-node /deep/ .el-switch__core { width: 35px; height: 15px; } .custom-tree-node /deep/ .el-switch__core::after { height: 12px; width: 12px; } .custom-tree-node { flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px; } </style>
3、使用示例
<template> <div> <switch-tree :treeData="data" @openswitch="openOrCloseSwitch" ></switch-tree> </div> </template> <script> import SwitchTree from "./SwitchTree.vue"; export default { name: "HelloWorld", components: { SwitchTree, }, props: { treeWith: { type: Number, default: 200, }, }, data() { return { filterText: "", data: [ { id: 1, label: "一級", isChecked: false, children: [ { id: 2, label: "二級 1-1", isChecked: false, children: [ { id: 3, label: "三級 1-1-1", isChecked: false, }, { id: 4, label: "三級 1-1-2", }, ], }, ], }, { id: 5, label: "一級", isChecked: true, }, ], }; }, methods: { openOrCloseSwitch(data) { if (data.isChecked) { console.log("open"); } else { console.log("close"); } }, }, }; </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>