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

相关推荐
儒雅的烤地瓜1 小时前
JS | JS中判断数组的6种方法,你知道几个?
javascript·instanceof·判断数组·数组方法·isarray·isprototypeof
道爷我悟了1 小时前
Vue入门-指令学习-v-on
javascript·vue.js·学习
27669582921 小时前
京东e卡滑块 分析
java·javascript·python·node.js·go·滑块·京东
PleaSure乐事1 小时前
【Node.js】内置模块FileSystem的保姆级入门讲解
javascript·node.js·es6·filesystem
雷特IT2 小时前
Uncaught TypeError: 0 is not a function的解决方法
前端·javascript
awonw2 小时前
[前端][easyui]easyui select 默认值
前端·javascript·easyui
老齐谈电商2 小时前
Electron桌面应用打包现有的vue项目
javascript·vue.js·electron
柏箱3 小时前
使用JavaScript写一个网页端的四则运算器
前端·javascript·css
一颗花生米。6 小时前
深入理解JavaScript 的原型继承
java·开发语言·javascript·原型模式
学习使我快乐016 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript