Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue树形组件

作者:Angel★狂龙   发布日期:2026-01-06   浏览:52

<template>
  <div class="tree">
    <ul>
      <tree-node 
        v-for="(node, index) in treeData" 
        :key="index" 
        :node="node"
      />
    </ul>
  </div>
</template>

<script>
import TreeNode from './TreeNode.vue';

export default {
  name: 'Tree',
  components: {
    TreeNode
  },
  data() {
    return {
      treeData: [
        {
          id: 1,
          label: 'Node 1',
          children: [
            { id: 2, label: 'Child Node 1' },
            { id: 3, label: 'Child Node 2' }
          ]
        },
        {
          id: 4,
          label: 'Node 2',
          children: [
            { id: 5, label: 'Child Node 3' }
          ]
        }
      ]
    };
  }
};
</script>

<style scoped>
.tree ul {
  list-style-type: none;
  padding-left: 20px;
}
</style>

解释说明

  1. 模板部分 (<template>):

    • 使用了一个 ul 列表来展示树形结构。
    • 使用了自定义组件 TreeNode 来递归渲染每个节点。通过 v-for 指令遍历 treeData,并将每个节点传递给 TreeNode 组件。
  2. 脚本部分 (<script>):

    • 导入了 TreeNode 组件。
    • 定义了 Tree 组件,并在 components 中注册了 TreeNode
    • data 中定义了 treeData,这是一个包含多个节点及其子节点的数组。
  3. 样式部分 (<style scoped>):

    • 为树形结构的 ul 元素设置了样式,去除了默认的列表样式,并增加了缩进以表示层级关系。

TreeNode.vue (递归组件)

<template>
  <li>
    {{ node.label }}
    <ul v-if="node.children && node.children.length">
      <tree-node 
        v-for="(child, index) in node.children" 
        :key="index" 
        :node="child"
      />
    </ul>
  </li>
</template>

<script>
export default {
  name: 'TreeNode',
  props: {
    node: {
      type: Object,
      required: true
    }
  }
};
</script>

解释说明

  • 模板部分 (<template>):

    • 每个 TreeNode 组件渲染一个 li 元素,显示节点的 label
    • 如果该节点有子节点,则递归地渲染子节点。
  • 脚本部分 (<script>):

    • 定义了 TreeNode 组件,并接收 node 作为属性。
    • 通过 props 接收父组件传递的 node 数据。

这样,整个树形结构就可以通过递归组件的方式动态生成和展示。

上一篇:vue @change

下一篇:vue 字符串

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

vue3组件传值的方式

vue3 子路由

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站