element官网上的树型控件自定义节点内容部分只有删除和添加结点,但是我想修改其中的某一条结点。一开始的想法是在每个结点后面都加一个编辑按钮,点击后弹一个对话框,对话框里写一个输入框修改。但后面想想每次都弹一个对话框的话用户体验太差了,于是就想到了直接在树型控件中嵌入输入框修改内容的方法,效果如下。
1.引入 (nextTick用于等待DOM更新)
import { ref } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { nextTick } from 'vue'
2.模板内容(大部分跟官网一样,只加了编辑按钮和输入框,主要加了v-if和v-else的判断)
<template>
<div class="custom-tree-container">
<el-tree
style="max-width: 600px"
:data="dataSource"
node-key="id"
default-expand-all
:expand-on-click-node="false"
>
<template #default="{ node, data }">
<span class="custom-tree-node">
<span v-if="node.label">{{ node.label }}</span>
<span v-else><el-input v-model="treeInputText" ref="treeInput" @blur="changTree(node,data)" style="width: 150px; height: 20px;" placeholder="Please input" /></span>
<span>
<a style="color: #67c23a" @click="edit(node, data)"> 编辑 </a>
<a style="margin-left:8px; color:#409eff" @click="append(data)"> 添加 </a>
<a style="margin-left:8px; color:#f56c6c" @click="remove(node, data)"> 删除 </a>
</span>
</span>
</template>
</el-tree>
</div>
</template>
3.提供数据和方法
//Tree控件的数据模型
interface Tree {
id: number
label: string
children?: Tree[]
}
//数据模型
const dataSource = ref([
{
id: 1,
label: '第一章',
children: [
{
id: 4,
label: '1-1',
children: [
{
id: 9,
label: '1-1-1',
},
{
id: 10,
label: '1-1-2',
},
],
},
],
}
])
let id = 1000
//添加数据方法
const append =async (data: Tree) => {
const newChild = { id: id++, label: '', children: [] }
if (!data.children) {
data.children = []
}
data.children.push(newChild)
dataSource.value = [...dataSource.value]
console.log(dataSource.value);
//等待DOM更新,并获取焦点
await nextTick()
treeInput.value.focus()
}
//删除数据方法(跟官网一样,没变)
const remove = (node: Node, data: Tree) => {
const parent = node.parent
const children: Tree[] = parent.data.children || parent.data
const index = children.findIndex((d) => d.id === data.id)
children.splice(index, 1)
dataSource.value = [...dataSource.value]
}
//修改数据方法
const edit = async (node: Node, data: Tree) => {
//先获取结点数据赋值给输入框,然后清空结点数据,这时触发模板中的else显示输入框
treeInputText.value = data.label
data.label = ""
//等待DOM更新,必须要这一句否则会因为输入框还没显示,获取不到输入框
await nextTick()
treeInput.value.focus() //聚焦输入框
}
const treeInput = ref() //输入框实例
const treeInputText = ref("") //输入框内容
//输入框失焦时触发
const changTree = (node,data)=>{
if(treeInputText.value === ""){
//用户没有输入,删除该结点
remove(node,data)
}
//输入不为空时
//1.先把输入框的内容赋值给结点,并清空输入框
data.label=treeInputText.value
treeInputText.value=""
}
4.最后是样式(copy官网的)
<style>
.custom-tree-node {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
padding-right: 8px;
}
</style>