vuepress 中使用 vue 组件

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div>
<button @click="change">{{buttonName}}</button>
</div>
</template>

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

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

vuepress 中使用 highlight 高亮代码

  1. 安装 highlight
1
npm i highlight -D
  1. 在组件中引入
1
2
3
4
5
6
7
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 以实现高亮
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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 的时候引入
1
2
3
4
5
6
7
8
9
10
created() {
import("prismjs/prism").then(Prism => {
this.Prism = Prism;
this.codeHtml = this.Prism.highlight(
code,//想要高亮的内容
this.Prism.languages.css,
"css"
);
});
},
  1. 在 code 内容发生变化时
1
2
3
if (code) {
this.codeHtml = this.Prism.highlight(code, this.Prism.languages.css, 'css');
}
  1. 在模板中使用
1
<code class="language-css" v-html="this.codeHtml"></code>