需求:
Element plus的樹組件實現單選和搜索功能。
效果:
實現:
<!-- element plus 樹組件實現單選及搜索功能 --> <template> <div class="tree-radio"> <h3>Element plus 樹組件實現單選及搜索功能</h3> <hr /> <el-input type="text" v-model="filterText" placeholder="請輸入搜索內容" /> <hr /> <div class="tree"> <el-tree :data="treeData" :props="{ label: 'label', children: 'children', class: customNodeClass, }" node-key="id" ref="treeForm" show-checkbox check-strictly default-expand-all :filter-node-method="filterNode" @check-change="handleCheckChange" /> </div> <hr /> <el-button type="primary" @click="getCheckedTree" >獲取選中的節點</el-button > </div> </template> <script> // 給節點添加class const customNodeClass = (data) => { if (data.isPenultimate) { return 'no-checkbox-node'; } return null; }; export default { name: 'tree-radio', data() { return { customNodeClass, filterText: '', checkedId: '', treeData: [ { id: '1', label: '標簽1', isPenultimate: true, children: [ { id: '1-1', label: '標簽1-1', }, { id: '1-2', label: '標簽1-2', }, ], }, { id: '2', label: '標簽2', isPenultimate: true, children: [ { id: '2-1', label: '標簽2-1', isPenultimate: true, children: [ { id: '2-1-1', label: '標簽2-1-1', }, { id: '2-1-2', label: '標簽2-1-2', }, ], }, { id: '2-2', label: '標簽2-2', isPenultimate: true, children: [ { id: '2-2-1', label: '標簽2-2-1', }, { id: '2-2-2', label: '標簽2-2-2', }, ], }, ], }, ], }; }, watch: { // 過濾操作 filterText(val) { this.$refs.treeForm.filter(val); }, }, methods: { // 過濾節點 filterNode(value, data) { if (!value) return true; return data.label.indexOf(value) !== -1; }, // 單選操作 handleCheckChange(data, checked) { if (checked) { this.checkedId = data.id; this.$refs.treeForm.setCheckedKeys([data.id]); } else { if (this.checkedId === data.id) { this.$refs.treeForm.setCheckedKeys([data.id]); } } }, // 獲取單選選中的結果 getCheckedTree() { alert(`當前選中的節點為:${this.checkedId}`); }, }, }; </script> <style lang="less"> // 樣式重置,記得把 scoped 屬性去掉才能生效 .tree-radio { border: 1px solid #ddd; padding: 20px; border-radius: 5px; h3 { font-weight: 300; color: #ff9b61; font-size: 18px; } width: 500px; margin: 100px auto; .no-checkbox-node { & > .el-tree-node__content { .el-checkbox { display: none; } } } .el-checkbox__inner { border-radius: 50%; } } </style>