
vue-code-view是一个基于 vue 2.x、轻量级的代码交互组件,在网页中实时编辑运行代码、预览效果的代码交互组件。
使用此组件, 不论 vue 页面还是 Markdown 文档中的示例代码,效果如下:
当项目中页面或者 Markdown 文档包含大量代码时,使用 highlight.js 进行代码高亮后极大的增大了阅读性,但是当我们阅读时想要对当前代码进行编辑调试时,只能打开本地开发环境或者跳转至 codepen codesandbox等在线项目示例。即使是很简单的代码示例仍然避免不了上述场景的繁琐步骤!如果遇到网络不好,或者本地开发环境没有安装配置的情况,那就很遗憾了!
目前大多开源项目的 Markdown 文档示例大多支持了示例代码的实时渲染,可以在文档页面中看到源码的运行效果,提供了在线项目的跳转功能。当需要调试代码时,还是需要重复上述步骤,体验不是太友好。
那么能不能有这么一个组件能支持在页面中编辑代码,实时运行预览效果?在网络找了好久,没有找到 vue 版本,只看到了 react-code-view,受其启发,自已编写了一个 vue 版本组件 vue-code-view !
目前组件已实现的主要功能特性:
SFC 解析,支持 <template> <script> <style>代码逻辑。<style> CSS 预处理,目前实现sass。Markdown 示例实时渲染,需要自定义 loader 。| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| theme | theme mode,支持 light / dark | light | dark | dark |
| showCode | 是否显示代码编辑器 | boolean | false |
| source | 示例代码 | string | - |
| renderToolbar | 自定义工具栏展示 | function | - |
| errorHandler | 错误处理函数 | function | - |
| debounceDelay | 错误处理防抖延迟(ms) | number | 300 |
Github 项目地址:vue-code-view
项目网站及在线示例: vue-code-view
NPM 地址: vue-code-view
使用 npm 或 yarn 安装组件包。
npm i vue-code-view # or yarn add vue-code-view 组件使用包含运行时编译器的 Vue 构建版本,所以需要单独配置下。
若使用 vue cli,需要在vue.config.js文件进行如下配置:
module.exports = { runtimeCompiler: true, // or chainWebpack: (config) => { config.resolve.alias .set("vue$", "vue/dist/vue.esm.js"); }, }; 在项目的入口文件 main.js 中引入组件及样式,注册组件。
import Vue from "vue"; import App from "./App.vue"; import CodeView from "vue-code-view"; import "vue-code-view/lib/vue-code-viewer.css"; ... Vue.use(CodeView); ... 使用组件的source属性传入示例代码。
示例代码格式支持 <template> <script> <style>,<template>不能为空;暂不支持JSX 语法。
<template> <div id="app"> <code-viewer :source="code_example"></code-viewer> </div> </template> <script> const code_source = ` <template> <div id="app"> <img alt="Vue logo" class="logo" src="https://cn.vuejs.org/images/logo.svg" /> <h1>Welcome to Vue.js {{version}} !</h1> </div> </template> <script> export default { data() { return { version: '2.x' }; }, }; <\/script> <style> .logo { width:66px; } </style> `, export default { data() { return { code_example: code_source }; }, }; </script> JSX使用方式组件 JSX 语法使用方式。
<script> const code_example = `<template> <div id="app"> <img alt="Vue logo" class="logo" src="https://cn.vuejs.org/images/logo.svg" /> <h1>Welcome to Vue.js !</h1> </div> </template> `; export default { name: "demo", render() { return ( <div > <code-viewer source={code_example} showCode={false} ></code-viewer> </div> ); }, }; </script> 项目引入其他组件库后,组件的示例源代码中直接使用即可,实现预览调试功能。
组件内置了错误预处理,目前支持代码为空、代码格式错误(<template>内容不存在)等,以文字的形式显示在示例区域,也提供了自定义错误方式 errorHandler(使用 Notice 组件进行信息告知)。
render() { return ( <div > <code-viewer source={code_example} showCode={false} errorHandler={(errorMsg) => { this.$notify.error({ title: "Info", message: errorMsg, }); }} ></code-viewer> </div> ) } 示例使用了antd vue 的 notify组件进行消息提醒,效果如下:
具体示例效果详见 组件 Markdown 说明文档