elementui append
ElementUI append 方法的使用
ElementUI 的 append 方法通常用于树形组件(el-tree)或上传组件(el-upload),用于动态添加节点或文件。以下是具体用法:
在 el-tree 中使用 append 方法
el-tree 的 append 方法用于向指定节点添加子节点。需要结合 node 对象和 data 数据操作。
// 示例:向树形组件添加子节点
handleAppend(node, data) {
const newChild = { id: ++this.maxId, label: '新节点', children: [] };
if (!data.children) {
this.$set(data, 'children', []);
}
data.children.push(newChild);
}
模板部分需绑定 append 事件:
<el-tree
:data="treeData"
node-key="id"
@node-append="handleAppend">
</el-tree>
在 el-upload 中使用 append 方法
el-upload 的 append 方法用于手动添加文件到上传列表。通常通过 ref 调用组件的内部方法。
// 示例:手动追加文件
this.$refs.upload.uploadFiles.push({
name: 'file.txt',
raw: new File(['content'], 'file.txt')
});
动态数据绑定的注意事项
- 在修改树形数据时,确保使用
this.$set或直接替换整个数组以触发响应式更新。 - 上传组件的文件列表需通过
:file-list绑定,避免直接操作 DOM。
完整示例代码
<template>
<el-tree
:data="treeData"
node-key="id"
@node-append="handleAppend">
<span slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<el-button @click="() => handleAppend(node, data)">添加子节点</el-button>
</span>
</el-tree>
</template>
<script>
export default {
data() {
return {
treeData: [{
id: 1,
label: '根节点',
children: []
}],
maxId: 1
};
},
methods: {
handleAppend(node, data) {
const newChild = { id: ++this.maxId, label: '新节点', children: [] };
if (!data.children) {
this.$set(data, 'children', []);
}
data.children.push(newChild);
}
}
};
</script>
通过以上方式,可以灵活实现动态数据追加功能。







