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

相关推荐
dly_blog1 小时前
Vue 响应式陷阱与解决方案(第19节)
前端·javascript·vue.js
消失的旧时光-19431 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
console.log('npc')1 小时前
Table,vue3在父组件调用子组件columns列的方法展示弹窗文件预览效果
前端·javascript·vue.js
我命由我123452 小时前
SVG - SVG 引入(SVG 概述、SVG 基本使用、SVG 使用 CSS、SVG 使用 JavaScript、SVG 实例实操)
开发语言·前端·javascript·css·学习·ecmascript·学习方法
C_心欲无痕2 小时前
vue3 - markRaw标记为非响应式对象
前端·javascript·vue.js
qingyun9893 小时前
深度优先遍历:JavaScript递归查找树形数据结构中的节点标签
前端·javascript·数据结构
胡楚昊3 小时前
NSSCTF动调题包通关
开发语言·javascript·算法
熬夜敲代码的小N3 小时前
Vue (Official)重磅更新!Vue Language Tools 3.2功能一览!
前端·javascript·vue.js
小彭努力中3 小时前
1.在 Vue 3 中使用 Cesium 快速展示三维地球
前端·javascript·vue.js·#地图开发·#cesium·#vue3
一棵开花的树,枝芽无限靠近你3 小时前
【face-api.js】1️⃣基于Tensorflow.js的人脸识别项目开源项目
javascript·开源·tensorflow·face-api.js