vue2 封装element ui tree 组件
时间: 2023-09-05 22:14:25 浏览: 395
Vue2 封装 Element UI Tree 组件的步骤如下:
1. 安装 Element UI
```bash
npm install element-ui --save
```
2. 在 main.js 中引入 Element UI
```js
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
```
3. 创建 Tree.vue 组件
```vue
<template>
<el-tree
:data="data"
:props="defaultProps"
@node-click="handleNodeClick">
</el-tree>
</template>
<script>
export default {
name: 'Tree',
props: {
data: {
type: Array,
default: () => []
},
defaultProps: {
type: Object,
default: () => ({
children: 'children',
label: 'label'
})
}
},
methods: {
handleNodeClick(node) {
this.$emit('node-click', node)
}
}
}
</script>
```
4. 在需要使用 Tree 的组件中引入 Tree 组件
```js
import Tree from './Tree.vue'
export default {
name: 'MyComponent',
components: {
Tree
},
data() {
return {
treeData: [
{
label: '一级 1',
children: [
{
label: '二级 1-1',
children: [
{
label: '三级 1-1-1'
},
{
label: '三级 1-1-2'
}
]
},
{
label: '二级 1-2',
children: [
{
label: '三级 1-2-1'
},
{
label: '三级 1-2-2'
}
]
}
]
},
{
label: '一级 2',
children: [
{
label: '二级 2-1',
children: [
{
label: '三级 2-1-1'
},
{
label: '三级 2-1-2'
}
]
},
{
label: '二级 2-2',
children: [
{
label: '三级 2-2-1'
},
{
label: '三级 2-2-2'
}
]
}
]
}
],
defaultProps: {
children: 'children',
label: 'label'
}
}
},
methods: {
handleNodeClick(node) {
console.log(node)
}
}
}
```
5. 在组件模板中使用 Tree 组件
```vue
<template>
<div>
<tree
:data="treeData"
:default-props="defaultProps"
@node-click="handleNodeClick">
</tree>
</div>
</template>
```
阅读全文