在vuepress中使用vue组件和highlight

vuepress 中使用 vue 组件

       在 vuepress 中一般会直接写 md 文件,但是有时需要做一些自定义的东西,比如展示一些前端效果,点击切换样式等等,就可以结合 vue 组件来实现。

1.在.vuepress 文件夹中建立 components 文件夹,添加一个例如名为 my-demo.vue 的文件

<template>
  <div>
    <button @click="change">{{buttonName}}</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      buttonName: "点击按钮"
    };
  },
  methods: {
    change() {
      console.log(111);
    }
  }
};
  1. 在 docs 下的 md 文件中使用
<ClientOnly>
  <my-demo></my-demo>
</ClientOnly>

注:直接按照组件名字使用即可,但是 md 文件外包裹文件夹会调不到组件,待观察。

vuepress 中使用 highlight 高亮代码

  1. 安装 highlight
  npm i highlight -D
  1. 在组件中引入
created() {
  //主题css,可自选
  import("highlight.js/styles/paraiso-dark.css");
  import("highlight.js/lib/index.js").then(hljs => {
    hljs.initHighlightingOnLoad();
  });
}
  1. 在 template 中使用 pre、code 包裹代码即可,highlight会将包裹的字符串进行标签包裹处理,加上class以实现高亮
<pre><code class="javascript"> 
  test = { 
      name : function () { 
          return 'hello'; 
      }, 
      age : function () { 
          return 13; 
      } 
  } 
</code></pre>
<pre><code class="css"> .a{
    background: red
}
</code></pre>

最终页面上的实现效果:
在这里插入图片描述

vuepress 中使用 Prism 高亮代码

       在实际开发过程中,想在 code 标签中修改内容,用 highlight 不知道怎么做,所以尝试用 Prism 高亮代码

  1. 在 created 的时候引入
created() {
  import("prismjs/prism").then(Prism => {
    this.Prism = Prism;
    this.codeHtml = this.Prism.highlight(
      code,//想要高亮的内容
      this.Prism.languages.css,
      "css"
    );
  });
},
  1. 在 code 内容发生变化时
if (code) {
  this.codeHtml = this.Prism.highlight(code, this.Prism.languages.css, 'css');
}
  1. 在模板中使用
<code class="language-css" v-html="this.codeHtml"></code>
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值