Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write an online help documentation tool based on vite2+Vue3

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to write an online help documentation tool based on vite2+Vue3". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to write an online help documentation tool based on vite2+Vue3.

Technology stack

Vite: ^ 2.7.0

Vue: ^ 3.2.23

Axios: ^ 0.25.0 get configuration and documentation in json format

Element-plus: ^ 2.0.2 UI Library

Nf-ui-elp ": ^ 0.1.0 second encapsulated UI library

@ element-plus/icons-vue: ^ 0.2.4 icon

@ kangc/v-md-editor: "^ 2.3.13 md Editor

Vite-plugin-prismjs: ^ 0.0.8 Code highlight

Nf-state ": ^ 0.2.4 status management

Nf-web-storage ": ^ 0.2.3 access indexedDB

Set up a library project (@ naturefw/press-edit) to realize the functions of document writing and browsing

First set up a Vue3 project using vite2:

Install elementPlus to achieve page effect

Install v-md-editor to realize the editing and display of Markdown

Install @ naturefw/storage operation indexedDB to store help documents

Install @ naturefw/nf-state to implement state management

Install axios is used to load json files to achieve the import function.

Write a back-end API with node to achieve the function of writing json files.

Note: the library project needs to install the above plug-ins, while the help documentation project only needs to install @ naturefw/press-edit.

Two states: edit and browse

At the beginning, I did two projects to achieve the functions of editing the document and displaying the document, but later found that most of the internal code was the same, and it was a bit troublesome to maintain it, so it was changed to add the status of "browse" in the project of editing the document, and then set the switching function to facilitate the maintenance of the internal code, which may be divided into two separate projects when it matures.

The function of editing statu

Menu maintenance

Document maintenance

Document presentation

Import and export

Write / execute code online

I like online editing, which makes it easier, so I use el-menu to implement navigation and the menu on the left, and then add maintenance. Use v-md-editor to edit and display Markdown. Then use node to write a back-end API to achieve the function of saving json files, which is perfect.

The ability to browse statu

Navigation

Menu

Document presentation

Execute the code

It is to remove some functions on the basis of editing the state. Or you can actually think the other way around.

Implement navigation

First of all, refer to VuePress to set up a json file, which is used to load and save website information and navigation information.

/ public/docs/.nfpress/project.json

{"projectId": "1000", "title": "nf-press-edit!" , "description": "this is a gadget for editing and displaying documents online", "navi": [{"naviId": "1010", "text": "Guide", "link": "menu"}, {"naviId": "1020", "text": "components", "link": "menu"} {"naviId": "1380", "text": "Gitee", "link": "https://gitee.com/nfpress/nf-press-edit"}, {" naviId ":" 1390 "," text ":" online presentation "," link ":" https://nfpress.gitee.io/nf-press-edit/"}, {"naviId": "1395" "text": "I want to make comments", "link": "https://gitee.com/nfpress/nf-press-edit/issues"}]}

ProjectId: project ID, which can be used to distinguish between different help documentation projects.

Navi: stores navigation items.

NaviId: associate to the menu.

Text: the text displayed on the navigation.

Link: connection method or link address. Menu: to open the corresponding menu; URL: to open the connection in the new page.

Then make a component and render it with el-menu binding data to achieve the navigation effect.

/ lib/navi/navi.vue

{{item.text}}

Can be multi-level navigation, there is no online maintenance function for the time being.

Import {ref} from 'vue' import {ElMenu, ElMenuItem} from' element-plus' import {state} from'@ naturefw/nf-state' const props = defineProps ({'background-color': {/ / default background color type: String, default:' # ece5d9'}, itemProps: Object}) / / get status and navigation content const {current NaviList} = state / / activate the first navigation item const activeIndex2 = ref (naviList [0] .naviId) const handleSelect = (key, keyPath) = > {const navi = naviList.find ((item) = > item.naviId = key) if (navi.link = = 'menu') {/ / Open menu current.naviId = key} else {/ / Open connection window.open (navi.link,' _ blank')}}

@ naturefw/nf-state

A lightweight state management written by yourself can be used as a large reactive, loading project.json through state management and then binding rendering.

NaviList

Navigation list, loaded by state management.

Current

Various information that is currently active, such as "current.naviId" represents the active navigation item.

Implement menu

Similar to navigation, except that two functions need to be added: n-level grouping and maintenance.

First of all, refer to VuePress to set up a json file to save menu information.

/ public/docs/.nfpress/menu.json

[{"naviId": "1010", "menus": [{"menuId": "110100", "text": "introduction", "description": "description", "icon": "FolderOpened", "children": []}, {"menuId": "111100", "text": "get started" "description": "description", "icon": "FolderOpened", "children": [{"menuId": 111120, "text": "Edit document Project", "description": "", "icon": "UserFilled", "children": []} {"menuId": 111130, "text": "Show document Project", "description": "," icon ":" UserFilled "}]]," ver ": 111130}, {" naviId ":" 1020 " "menus": [{"menuId": "21000", "text": "docNavi", "description": "description", "icon": "Star", "children": []}], "ver": 1.5}]

NaviId: the associated navigation item ID, which can be either a number or another character. It needs to correspond to the navigation item ID.

Menus: the collection of menu items corresponding to the navigation item.

MenuId: menu item ID, which is associated with a document, which can be numeric or English.

Text: name of the menu item.

Description: description, considering future use for queries.

Icon: the name of the icon used by the menu.

Children: submenu items. If not, you can remove them.

Ver: version number, easy to update the document.

Then use el-menu to bind data rendering, because you want to achieve n-level grouping, so do a recursive component to achieve the effect of n-level menu.

Implement n-level grouping menu

Make a recursive component to realize the function of n-level grouping:

/ lib/menu/menu-sub-edit.vue

{{item.text}} {{item.text}} import {ElMenuItem ElSubMenu} from 'element-plus' / / Show submenu-Recursive import mySubMenu2 from'. / menu-sub.vue' const props = defineProps ({subMenu: Array, / / menu to be displayed Can n-level dialogAddInfo: Object, / / add menu dialogModInfo: Object / / modify menu})

Submenu items to be displayed by subMenu

DialogAddInfo add menu information

DialogModInfo modifies menu information

Realize the maintenance function of the menu

This is relatively simple, do a form to achieve the addition, deletion and modification of the menu, space is limited to skip.

Implement the editing of Markdown

Use v-md-editor to edit and display Markdown. First of all, the plug-in is very easy to use, and secondly, it supports the theme of VuePress.

Set up / lib/md/md-edit.vue to realize the function of editing Markdown:

Import {watch,ref} from 'vue' import {ElMessage, ElRadioGroup, ElRadioButton} from' element-plus' import mdController from'. / service/md.js' / / status import {state} from'@ naturefw/nf-state' / / get the currently active information const current = state.current / / load and save const {loadDocById of the document SaveDoc} = mdController () / / visible height const editHeight = document.documentElement.clientHeight-200 / / Click the Save button Implement the save function const mySave = (text, html) = > {saveDoc (current)} / / timing save let timeout = null let isSaved = true const timeSave = () > {if (isSaved) {/ / saved, re-timing isSaved = false} else {return / / has timing Exit} timeout = setTimeout (() = > {/ / Save the document saveDoc (current). Then () = > {ElMessage ({message: 'automatically save the document successfully!' , type: 'success',})}) isSaved = true}, 10000)} / / Save the document regularly watch (() = > current.docInfo.md, () = > {timeSave ()}) / / based on the active menu item Load the corresponding document watch (() = > current.menuId, async (id) = > {const ver = current.ver loadDocById (id, ver). Then ((res) = > {/ / found document Object.assign (current.docInfo, res)}) .catch ((res) = > {/ / No document Object.assign (current.docInfo, res)})})

MdController realizes the controller of adding, deleting, changing and querying documents.

TimeSave saves the document regularly to avoid forgetting to click the save button

Isn't it easy.

Realize the function of writing code online and running it.

Because the project is based on Vue3 and is designed to write vue3-related help documentation, there is a practical requirement: write code online and run it.

Personally, I feel that this function is still very practical. I know that there are third-party websites that provide this function, but the network speed is a little slow, and there is a feeling of cannon hitting mosquitoes. I just need to implement a simple code demonstration.

So I wrote a simple version of the online coding and running function based on vue's defineAsyncComponent:

/ lib/runCode/run.vue

Import {defineAsyncComponent, ref, reactive,... / / other commonly used vue built-in instructions} from 'vue' / / compile js code const mysetup = `(function setup () {[code]}})` / / pass in the code and template const props = defineProps ({code: {type: Object) through attributes. Default: () = > {return {js:', template:', style:'}) const code = props.code / / use defineAsyncComponent to make the code run const AsyncComp = defineAsyncComponent () = > new Promise ((resolve, reject) = > {resolve ({template: code.template) / / set template style: [code.style], / / probably style setting But there seems to be no effect setup: (props, ctx) = > {const tmpJs = code.js / / get the js code let fun = null / / converted function try {if (tmpJs) fun = eval (mysetup.replace ('{[code]}') TmpJs)) / / use eval to turn a string into a function} catch (error) {console.error ('conversion exception:', error)} const re = typeof fun = = 'function'? Fun: () = > {} return {... re (props, ctx) / / run the function and deconstruct the returned object})}))

DefineAsyncComponent

For practical defineAsyncComponent loading components, you need to set up three parts: template, setup and style.

Template: string form, which can be passed directly

Setup: js code that can be dynamically compiled in the form of eval.

Style: styles can be set.

This allows code written online to run, of course, with limited functionality and can only be used for some simple code demos.

Export

All these functions are based on indexedDB, and if you want to release them, you need to export them as json files.

Because you can't write files directly in the browser, you need to use a compromise:

Copy and paste

download

Export

Copy and paste

This is simple, just display json in a text field.

download

Use the download function provided by the chrome browser to download the file.

Const uri = 'data:text/json;charset=utf-8,\ ufeff' + encodeURIComponent (show.navi) / / implement var link = document.createElement ("a") link.href = uri / / a pair of downloaded files named link.download = fileName document.body.appendChild (link) link.click () document.body.removeChild (link) by creating a tag

The above introduction is the internal principle, if you just want to use it simply, you can skip it and take a look at the introduction below.

Write files with the back end

Neither of the above is very convenient, so I use node to do a simple back-end API to achieve the function of writing json files.

The code is placed in the api folder and can be run using yarn api. Of course, you need to make some settings in package.json.

"scripts": {"dev": "vite", "build": "vite build-- mode project", "lib": "vite build-- mode lib", "serve": "vite preview", "api": "node api/server.js"}, implement a project that helps document

The above is the basic principles of the library project, when we want to do help documentation, it does not need to be that complicated.

Set up a vue3 project using vite2, and then install @ naturefw/press-edit, which can be easily implemented using the components provided.

Main.js

First of all, you need to make some settings in main.js.

Import {createApp} from 'vue'import App from'. / App.vue'// sets the baseUrlconst baseUrl of axios = _ (document.location.host.includes ('.gitee.io'))? / doc-ui-core/':'/'/ / lightweight status / / sets up the indexedDB database to store all kinds of information about the document. Import {setupIndexedDB SetupStore} from'@ naturefw/press-edit'// initializes indexedDB database setupIndexedDB (baseUrl) / / UI library import ElementPlus from 'element-plus'// import' element-plus/lib/theme-chalk/index.css'// import 'dayjs/locale/zh-cn'import zhCn from' element-plus/es/locale/lang/zh-cn'// secondary encapsulation import {nfElementPlus} from'@ naturefw/ui-elp'// setting iconimport installIcon from'. / icon/index .js'/ / sets the configuration function import setMarkDown from'. / main-md.js'// theme import vuepressTheme from'@ kangc/v-md-editor/lib/theme/vuepress.js'const {VueMarkdownEditor of Markdown / / Markdown editor VMdPreview / / Markdown browser} = setMarkDown (vuepressTheme) const app = createApp (App) app.config.globalProperties.$ELEMENT = {locale: zhCn, size: 'small'} app.use (setupStore) / / state management .use (nfElementPlus) / / re-packaged component .use (installIcon) / / register the global icon .use (ElementPlus, {locale: zhCn) Size: 'small'}) / / UI library .use (VueMarkdownEditor) / / markDown editor .use (VMdPreview) / / markDown shows .mount (' # app')

BaseUrl: set it according to the publishing platform. For example, you need to set it to "/ doc-ui-core/" here.

SetupIndexedDB: initialize the indexedDB database

SetupStore: setting statu

Element-plus:element-plus may not be mounted, but css needs import to come in, which is introduced here in the way of CDN.

NfElementPlus: a second packaged component, which is easy to add, delete, modify and query.

SetMarkDown: load the v-md-editor, as well as the required plug-ins.

VuepressTheme: sets the theme.

Set up Markdown

Because there are many settings related to v-md-editor, a separate file is set up for management:

/ src/main-md.js

/ / Markdown editor import VueMarkdownEditor from'@ kangc/v-md-editor'import'@ kangc/v-md-editor/lib/style/base-editor.css'// is introduced here and is not recognized? / / import vuepressTheme from'@ kangc/v-md-editor/lib/theme/vuepress.js'import'@ kangc/v-md-editor/lib/theme/style/vuepress.css'// Code highlights import Prism from 'prismjs'// emojiimport createEmojiPlugin from' @ kangc/v-md-editor/lib/plugins/emoji/index'import'@ kangc/v-md-editor/lib/plugins/emoji/emoji.css'// flowchart / / import createMermaidPlugin from'@ kangc/v-md- Editor/lib/plugins/mermaid/cdn'// import'@ kangc/v-md-editor/lib/plugins/mermaid/mermaid.css'// todoListimport createTodoListPlugin from'@ kangc/v-md-editor/lib/plugins/todo-list/index'import'@ kangc/v-md-editor/lib/plugins/todo-list/todo-list.css'// Code Line number import createLineNumbertPlugin from'@ kangc/v-md-editor/lib/plugins/line-number/index' / / highlight the code line import createHighlightLinesPlugin from'@ kangc/v-md-editor/lib/plugins/highlight-lines/index'import'@ kangc/v-md-editor/lib/plugins/highlight-lines/highlight-lines.css'// import createCopyCodePlugin from'@ kangc/v-md-editor/lib/plugins/copy-code/index'import'@ kangc/v-md-editor/lib/plugins/copy-code/copy-code.css'// markdown monitor import VMdPreview from'@ kangc/v -md-editor/lib/preview'// import'@ kangc/v-md-editor/lib/style/preview.css'/** * set the Markdown editor and browser * @ param {*} vuepressTheme * @ returns * / export default function setMarkDown (vuepressTheme) {/ / set the vuePress theme VueMarkdownEditor.use (vuepressTheme) {Prism, extend (md) {/ / md is a markdown-it instance You can modify the configuration here and use plugin for syntax extension / / md.set (option) .use (plugin) },}) / / Preview VMdPreview.use (vuepressTheme, {Prism, extend (md) {/ / md is a markdown-it instance, where you can modify the configuration and use plugin for syntax extension / / md.set (option) .use (plugin) } }) / / emoji VueMarkdownEditor.use (createEmojiPlugin ()) / / flowchart / / VueMarkdownEditor.use (createMermaidPlugin ()) / / todoList VueMarkdownEditor.use (createTodoListPlugin ()) / / Line number VueMarkdownEditor.use (createLineNumbertPlugin ()) / / highlighted line of code VueMarkdownEditor.use (createHighlightLinesPlugin ()) / / VueMarkdownEditor.use (createCopyCodePlugin ()) / / previewed plug-in VMdPreview.use (createEmojiPlugin ()) VMdPreview.use (createTodoListPlugin VMdPreview.use (createLineNumbertPlugin ()) VMdPreview.use (createHighlightLinesPlugin ()) VMdPreview.use (createCopyCodePlugin ()) return {VueMarkdownEditor VMdPreview}}

Without further introduction, you can choose plug-ins as needed.

Overall Arrangement

Make the overall layout in the App.vue file

Nf-press import {reactive, defineAsyncComponent} from 'vue' import {ElHeader, ElContainer, ElAside, ElMain} from' element-plus' import {docMenu, docNavi Config} from'@ naturefw/press-edit' / / menu navigation import docView from'. / views/doc.vue' / / display the document / / load the menu child control const docControl = {true: docView, false: defineAsyncComponent (() = > import ('. / views/main.vue')) / / modify the document} const itemProps = reactive ({'inline-prompt': true,' active-text': 'look' 'inactive-text':' write', 'active-color':' # 378FEBV, 'inactive-color':' # EA9712'})

$state: global status, whether the $state.current.isView setting is browsing status.

Doc-navi: navigation component

Doc-menu: menu component

DocControl: load the display component or edit the dictionary of the component according to the state.

Although this method is a bit troublesome, it is more flexible, and can be flexibly set up according to needs, such as adding copyright information, filing information, advertising and other content.

At this point, I believe you have a deeper understanding of "how to write an online help documentation tool based on vite2+Vue3". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report