使用el-aside和el-main布局,实现el-tree和el-form相结合的左树右表结构。表单参照Form 表单使用,下面主要说明el-tree的常见使用方法:

<el-aside>
<el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
<el-button type="primary" icon="el-icon-plus" size="small" @click="addChanel" style="width:100%;margin:7px 0;">添加栏目</el-button>
<el-scrollbar class="scrollbar">
<el-tree
ref="tree"
:data="treeData"
:props="defaultProps"
node-key="id"
:default-checked-keys="defaultCheckedKeys"
default-expand-all
@node-click="nodeClick"
:filter-node-method="filterNode">
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button v-show="data.label!='所有栏目'" icon="el-icon-edit" type="text" size="mini" @click.stop="editChannel(data)"> </el-button>
<el-button v-show="data.label!='所有栏目'" icon="el-icon-delete" type="text" size="mini" @click.stop="rowDelete(node, data)"></el-button>
</span>
</span>
</el-tree>
</el-scrollbar>
</el-aside>
data() {
return {
filterText: '',
channelId:'',
treeData :[]
}
},
watch: {
filterText(val) {
this.$refs.tree.filter(val);
}
},
method:{
//对树节点进行筛选操作
filterNode(value, data) {
if (!value) return true;
return data.name.indexOf(value) !== -1;
},
//节点被点击时的回调
nodeClick(data) {
this.channelId=data.id
},
//获取树数据
getChannelTree() {
getChannelTree().then(response => {
this.treeData = response.data.data
this.$nextTick(() => {
this.$refs.tree.setCurrentKey(this.channelId);
})
// this.$refs.tree.setCurrentKey(this.channelId);
})
},
}
<style lang="scss" scoped>
/*分类树增加边框样式*/
.el-aside{
border:1px solid #e7e8eb;
}
/*分类树增加滚动样式*/
.scrollbar{
/*height: calc(100% - 80px);*/
height: 600px;
}
.scrollbar /deep/ .el-scrollbar__wrap{
overflow-x: hidden;
}
/*分类树编辑删除按钮样式*/
div /deep/ .custom-tree-node{
flex: 1;
display:flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
padding-right: 8px;
}
</style>
一、输入关键字过滤树节点



二、对树增加滚动条,避免过长
在el-tree外层用包裹,然后设置高度样式



三、分类树编辑删除按钮样式调整
调整前:

调整后:


四、设置选中当前某个树节点
setCurrentKey,通过 key 设置某个节点的当前选中状态,使用此方法必须设置 node-key 属性,然后在节点被点击的node-click事件中将该节点id存起来,最后在刷新树事件里或者在需要的地方设置选中该节点this.$refs.tree.setCurrentKey(this.channelId);


这个设置有个坑,但是在数据请求完后,获取到treeData,然后设置this.refs.tree.setCurrentKey()当前被选中的节点,但是发现并无效果。
原因是:DOM并未渲染完,也就是被选中的树节点还没有渲染出来,所以对他的操作是无效的,需要借助nextTick,确保DOM已渲染。
this.$nextTick(() => {
this.$refs.tree.setCurrentKey(this.channelId);
})
$nextTick 是确保DOM渲染结束之后执行的。在项目中,我们常常会进行数据请求,获取数据之后,可能要对数据进行一些操作,比如说在radio、checkbox、select等等,我们会默认选中某些值。
或者刚进入页面时,可能会对页面进行操作,一般会在mounted(){}里执行,比如说需要获取某个div的宽度、高度。但是并不确保DOM已渲染完,所以需要使用$nextTick,否则可能会报错:“TypeError: Cannot read property ‘clientHeight’ of null”。
本文介绍了el-tree组件的使用,包括通过输入关键字过滤树节点、为树添加滚动条、调整编辑删除按钮样式以及设置选中特定节点的方法。特别提到在设置选中节点时,由于DOM渲染问题,需要利用$nextTick确保操作生效。

3905

被折叠的 条评论
为什么被折叠?



