微信小程序多级折叠怎么实现?

新手上路,请多包涵

怎么在微信小程序用vue2语法实现一个多级折叠面板呀,

在插件市场找不到多级的折叠,自己尝试封装也失败了

阅读 1.1k
2 个回答

react写的,vue你改改就行了,就是个递归而已
111.gif

// App.js
import "./App.css";
// import ComA from "./comA";
// import ComB from "./comB";
import Menu from "./Menu";

function App() {
  return (
    <div className="App">
      <div>
        {/* <ComA />
        <ComB /> */}
        <Menu />
      </div>
    </div>
  );
}

export default App;
// Menu.js
import React from "react";
import MenuItem from "./MenuItem";

const Menu = () => {
  const menuData = [
    {
      id: 1,
      name: "Item 1",
      children: [
        {
          id: 2,
          name: "Item 1.1",
          children: [
            {
              id: 3,
              name: "Item 1.1.1",
            },
          ],
        },
      ],
    },
    {
      id: 4,
      name: "Item 2",
      children: [
        {
          id: 5,
          name: "Item 2.1",
        },
      ],
    },
  ];

  return (
    <div>
      {menuData.map((item) => (
        <MenuItem key={item.id} item={item} />
      ))}
    </div>
  );
};

export default Menu;
// MenuItem.js
import React, { useState } from "react";

const MenuItem = ({ item }) => {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = () => {
    setIsOpen(!isOpen);
  };

  return (
    <div>
      <div onClick={toggle} style={{ cursor: "pointer", fontWeight: "bold" }}>
        {item.name} {item.children && (isOpen ? "-" : "+")}
      </div>
      {isOpen && item.children && (
        <div style={{ marginLeft: "20px" }}>
          {item.children.map((child) => (
            <MenuItem key={child.id} item={child} />
          ))}
        </div>
      )}
    </div>
  );
};

export default MenuItem;

写了一个很简单的组件递归调用,你要实现的多级主要是实现组件本身的递归调用,样式和事件可以自己尝试补充一下。

首先是外部调用组件:

<script>
import Tree from './components/tree.vue'
export default {
  name: '',
  components: { Tree },
  data() {
    return {
      treeList: [
        {
          name: '总部',
          children: [{ name: '研发部', children: [{ name: '研发一部' }, { name: '研发二组' }] }, { name: '行政部' }],
        },
        { name: '营销中心', children: [{ name: '营销一部' }, { name: '营销二部' }] },
      ],
    }
  },
}
</script>
<template>
  <Tree :data="treeList"></Tree>
</template>

组件内部实现:

<script>
export default {
  name: 'Tree',
  props: {
    data: {
      type: Array,
      default: [],
    },
  },
}
</script>
<template>
  <ul>
    <li v-for="item in data">
      {{ item.name }}
      <template v-if="item.children">
        <span>></span>
        <Tree :data="item.children"></Tree>
      </template>
    </li>
  </ul>
</template>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏