文章目录
- 前言
 - 实现
 - 
- 
- 安装依赖
 - vue.config.js配置
 - main.js 全局注册
 - 参数配置
 - 新建vue单文件
 - 组件库混合使用
 - 错误处理
 
 
 - 
 
前言
vue-code-view是一个基于 vue 2.x、轻量级的代码交互组件,在网页中实时编辑运行代码、预览效果的代码交互组件。
官方手册:
 Vue Code View
 参考文章:
 [个人开源]vue-code-view:一个在线编辑、实时预览的代码交互组件
 Vue Code View: A Vue 2 SFC REPL component
使用此组件, 不论 vue 页面还是 Markdown 文档中的示例代码,效果如下:

实现
安装依赖
npm i vue-code-view
# or
yarn add vue-code-view
vue.config.js配置
注意:这里用的是or(或)
module.exports = {
  runtimeCompiler: true,
  // or
  chainWebpack: (config) => { 
    config.resolve.alias
      .set("vue$", "vue/dist/vue.esm.js");
  },
}; 
main.js 全局注册
// vue-code-view
import CodeView from "vue-code-view";
Vue.use(CodeView);
参数配置
| 参数 | 说明 | 类型 | 默认值 | 版本 | 
|---|---|---|---|---|
| themeMode | 主题theme mode,默认light,支持 dark | `` 或 dark | `` | |
| showCode | 是否显示代码编辑器,只有在layout值为top生效 | boolean | false | |
| source | 运行示例源码 | string | - | |
| layout | render 视图布局 | top 或 right 或 left | top | 0.4.0 | 
个人感觉手册里配置写的不是很好,使用者不知道具体怎么使用,可以参考下面我的使用方法
新建vue单文件
<script>
const code_example = `<template>
  <div id="app">
    <img alt="Vue logo" class="logo" src="https://www.yuucn.com/wp-content/uploads/2023/05/1684248044-a9ca298e41e926e.png" />
    <h1>Welcome to Vue.js  !</h1>
  </div>
</template> `;
export default {
  name: "demo",
  render() {
    return (
      <div>
        <code-viewer
          source={code_example}
          showCode={true}
          layout={`right`}
          themeMode={`light`}
        ></code-viewer>
      </div>
    );
  },
};
</script>
<style scoped lang=scss>
/* code-viewer */
.vue-repl {
  height: 800px;
}
</style>
组件库混合使用
项目引入其他组件库后,组件的示例源代码中直接使用即可,实现预览调试功能

错误处理
组件内置了错误预处理,目前支持代码为空、代码格式错误(内容不存在)等,以文字的形式显示在示例区域,也提供了自定义错误方式 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组件进行消息提醒,效果如下:

下班~