前言
在PrimeVue中的Tree组件中,只能默认点击箭头,执行树节点的展开和折叠 在本文件中,进一步处理成:当选择当前根目录时,直接就可进行树节点的展开和折叠
1. 页面组件
expandAll ( ) :展开所有树节点 collapseAll ( ) :关闭所有树节点 :value=“nodes”:树数据 v-model:expandedKeys=“expandedKeys”:控制树的展开和折叠 #default=“slotProps”:自定义模板(显示树节点的标签文本) getColor ( level ):根据树的层次渲染文本颜色
< template>
< div class = "left-menu" >
< Loading ref= "loading" : isLoading= "isLoading" > < / Loading>
< div class = "btn-group" >
< Button type= "button" icon= "pi pi-plus" label= "展开" @click= "expandAll" / >
< Button type= "button" icon= "pi pi-minus" label= "折叠" @click= "collapseAll" / >
< / div>
< Tree
: value= "nodes"
v- model: expandedKeys= "expandedKeys"
class = "tree"
@nodeSelect= "onNodeSelect"
>
< template #default = "slotProps" >
< div : style= "{fontWeight:'bold', color: getColor(slotProps.node.level)}" >
{ { slotProps. node. label } }
< / div>
< / template>
< / Tree>
< / div>
< / template>
2. 引入Tree组件
import { ref} from "vue" ;
import Button from "primevue/button" ;
import Tree from "primevue/tree" ;
3. 初始化node对象
const nodes = ref ( null ) ;
const expandedKeys = ref ( { } ) ;
let isLoading = true ;
window. onload = function ( ) {
isLoading = true
fetchData ( )
}
async function fetchData ( ) {
try {
const response = await axios. get ( '请求数据URL' ) ;
const directoryTree = response. data[ 0 ] ;
const treeWithLevels = addLevelsToTreeNodes ( directoryTree) ;
nodes. value = [ treeWithLevels] ;
pickDirectory ( response. data)
expandedKeys. value = { } ;
} catch ( e) {
console. error ( e)
} finally {
isLoading = false ;
}
}
function addLevelsToTreeNodes ( node, level = 0 ) {
node. level = level;
if ( node. children) {
node. children. forEach ( child => addLevelsToTreeNodes ( child, level + 1 ) ) ;
}
return node;
}
4. 按钮事件及层次颜色函数
const expandAll = ( ) => {
for ( let node of nodes. value) {
expandNode ( node) ;
}
expandedKeys. value = { ... expandedKeys. value} ;
} ;
const collapseAll = ( ) => {
expandedKeys. value = { } ;
} ;
const expandNode = ( node ) => {
if ( node. children && node. children. length) {
expandedKeys. value[ node. key] = true ;
for ( let child of node. children) {
expandNode ( child) ;
}
}
} ;
const getColor = ( level ) => {
const colors = [ '#00a65a' , '#3c8dbc' , '#f39c12' , '#00c0ef' , '#e67ad2' ] ;
return level > colors. length ? '#d2d6de' : colors[ level] ;
}
5. 选择当前树目录事件
const onNodeSelect = async ( node ) => {
console. log ( node) ;
if ( node) {
expandedKeys. value[ node. key] = ! expandedKeys. value[ node. key] ;
} catch ( e) {
console. error ( e)
}
}
}
} ;