iView Tree 預設鉤選 - daniel-qa/Vue GitHub Wiki
<template>
<div class="test-component">
<Tree :data="treeData" show-checkbox ref="tree"></Tree>
</div>
</template>
<script>
export default {
name: 'TestComponent',
data() {
return {
treeData: [
{
title: '國語文',
key: 'chinese',
expand: true,
children: [
{ title: '第一冊', key: 'chinese-1' },
{ title: '第二冊', key: 'chinese-2' },
{ title: '第三冊', key: 'chinese-3' }
]
},
{
title: '數學',
key: 'math',
expand: true,
children: [
{ title: '第一冊', key: 'math-1' },
{ title: '第二冊', key: 'math-2' },
{ title: '第三冊', key: 'math-3' }
]
}
]
}
},
mounted() {
// 設定預設勾選項目
const defaultKeys = ['chinese-1', 'chinese-2'];
this.setDefaultCheckedNodes(defaultKeys);
},
methods: {
// 設定預設勾選的節點
setDefaultCheckedNodes(checkedKeys = []) {
this.$nextTick(() => {
if (this.$refs.tree) {
// 遍歷並設定每個節點為勾選狀態
checkedKeys.forEach(key => {
const targetNode = this.findNodeByKey(this.treeData, key);
if (targetNode) {
this.$set(targetNode, 'checked', true);
}
});
}
});
},
// 遞迴查找指定 key 的節點
findNodeByKey(nodes, key) {
for (let node of nodes) {
if (node.key === key) {
return node;
}
if (node.children && node.children.length > 0) {
const found = this.findNodeByKey(node.children, key);
if (found) {
return found;
}
}
}
return null;
}
}
}
</script>
<style scoped>
.test-component {
padding: 20px;
}
</style>
1 .添加 ref:在 Tree 組件上添加 ref="tree" 以便在程式中引用
2 .mounted 生命週期(第 37-48 行):
使用 $nextTick 確保 DOM 已完全渲染
調用 findNodeByKey 方法查找 'chinese-1' 節點
使用 $set 動態設定 checked: true 屬性
3 .findNodeByKey 方法(第 50-64 行):
遞迴查找樹狀結構中指定 key 的節點
支援多層級的節點查找
這種動態設定的方式更靈活,可以在組件載入後根據需要動態調整勾選狀態,而不是在資料初始化時硬編碼。
Feedback submitted