v-md-editor自定义锚点(生成目录)数组转树结构

接前两篇博文,最终方案终于定了,也把之前做的编辑器模式给否决了,原因是系统中有老的文档需要平替,因此就不能通过编辑器这种模式了,太麻烦了。

最终方案:线下手动pandoc word转markdown,然后将文档保存到前端(图片也在对应路径下)页面上菜单绑定文档,文档中自动生成目录;

issue

v-md-editor群里大佬提供了生成自定义锚点(目录)的方式,但是是数组平铺的,根据级别然后展示的时候通过距离形成视觉上的菜单,但是需求模型上是菜单可点击收缩打开方式的,因此,需要调整该数组为树结构,因为本人纯后端,在朋友帮助下,将数组转为了树

解决方法

js 复制代码
//0 1 2 3 代表菜单级别
const target = {
	"titles": [
		{"title:": "导读","lineIndex": "1","indent": 0},
		{"title:":"功能范围","lineIndex":"1","indent":1},
		{"title:":"寻求帮助","lineIndex":"1","indent":1},
		{"title:":"业务功能介绍","lineIndex":"1","indent":0},
		{"title:":"1.二级标题","lineIndex":"1","indent":1},
		{"title:":"1.1 三级标题","lineIndex":"1","indent":2},
		{"title:":"1.1.1四级","lineIndex":"1","indent":3},
		{"title:":"1.2 san级","lineIndex":"1","indent":2},
		{"title:":"2.四3级","lineIndex":"1","indent":1},
		{"title:":"2.1四2级","lineIndex":"1","indent":2}
	]
}

function getTree(titles) {
    const res = []
    let treeNodeList = []
    let last = null

    function getParentNode(index) {
        let currentIndex = index - 1
        while (!treeNodeList[currentIndex]) {
            currentIndex--
        }
        return treeNodeList[currentIndex]
    }

    for (let i = 0, l = titles.length; i < l; i++) {
        const item = titles[i]
        if (item.indent == 0) {
            res.push(item)
            treeNodeList = []
        } else {
            // 父节点
            const currentParent = getParentNode(item.indent)
            if (currentParent.children) {
                currentParent.children.push(item)
            } else {
                currentParent.children = [item]
            }
            if (last.indent > item.indent) {
                treeNodeList = treeNodeList.splice(0, item.indent)
            }
        }
        // 把自己放到节点队列中
        treeNodeList[Number(item.indent)] = item
        last = item
    }
    return res
}

console.log(JSON.stringify(getTree(target.titles)))

最终得到的转换后的结构

ps: 用后端逻辑开发前端真的是不好转换,总想着先去定义对象,结果根本没那么需要,强弱类型的开发方式真的太不同了。

相关推荐
Keepreal49642 分钟前
Web Components简介及如何使用
前端·javascript·html
进击的野人1 小时前
JavaScript变量声明的前世今生:从var到let/const的演进
javascript
柯腾啊2 小时前
“Script error.”的产生原因和解决办法
前端·javascript·浏览器
Cory.眼3 小时前
WebRTC入门指南:实时通信零基础
javascript·webrtc·实时通信
前端架构师-老李3 小时前
16 Electron 应用自动更新方案:electron-updater 完整指南
前端·javascript·electron
拖拉斯旋风3 小时前
📚 JavaScript 变量声明三剑客:`var`、`let`、`const` 学习笔记
javascript
可触的未来,发芽的智生5 小时前
追根索源:换不同的词嵌入(词向量生成方式不同,但词与词关系接近),会出现什么结果?
javascript·人工智能·python·神经网络·自然语言处理
努力写代码的熊大5 小时前
stack、queue与priority_queue的用法解析与模拟实现
java·前端·javascript
im_AMBER5 小时前
React 06
前端·javascript·笔记·学习·react.js·前端框架
m0_748233647 小时前
C++开发中的常用设计模式:深入解析与应用场景
javascript·c++·设计模式