【vue】vue 在线编辑、实时预览的代码交互组件 vue-code-view

前言

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生效booleanfalse
source运行示例源码string-
layoutrender 视图布局top 或 right 或 lefttop0.4.0

个人感觉手册里配置写的不是很好,使用者不知道具体怎么使用,可以参考下面我的使用方法

新建vue单文件

<script>
const code_example = `<template>
  <div id="app">
    <img alt="Vue logo" class="logo" src="http://rq2l4zm0j.hd-bkt.clouddn.com/chatGPT.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组件进行消息提醒,效果如下:

在这里插入图片描述

下班~

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fruge365

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值