# 1. 首先在项目中安装 prismjs 插件:

cnpm install prismjs -S

# 2. 安装完成后,需要继续安装一个 prismjs 的编译器插件

cnpm install babel-plugin-prismjs -D

# 3. 在.babelrc 文件中配置使用该插件:

{
  "plugins": [
    ["prismjs", {
      "languages": ["javascript", "css", "markup"],
      "plugins": ["line-numbers"],
      "theme": "twilight",
      "css": true
    }]
  ]
}

# 4. 封装

<template>
    <pre :class="'hx-scroll ' + lineNumbers">
    <code :class="'language-'+ type" v-html="showCode"></code>
 </pre>
</template>
<script>
import Prism from 'prismjs';
export default {
    name: 'prism',
    components: {},
    props: {
        code: {
            type: String,
            default: ''
        },
        type: {
            type: String,
            default: 'js'
        },
        isShowlineNumbers: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {};
    },
    computed: {
        lineNumbers() {
            return this.isShowlineNumbers ? 'line-numbers' : '';
        },
        showCode() {
            return Prism.highlight(this.code, Prism.languages[this.type], this.type);
        }
    },
    mounted() {
        Prism.highlightAll();
    },
    methods: {}
};
</script>
<style scoped></style>

# 5. 使用

<template>
    <div>
        <prview-code :code="code"></prview-code>
        <el-button type="primary" @click="handleFormula">公式弹窗</el-button>
        <el-button type="primary" @click="handleGroup">分组弹窗</el-button>
        <formula :dialogVisible.sync="visible" v-if="visible" />
        <group :dialogVisible.sync="groupVisible" v-if="groupVisible" />
    </div>
</template>
<script>
import prviewCode from '../tools/prismjs/Index.vue';
import formula from '../dialog/formula.vue';
import group from '../dialog/group.vue';
export default {
    name: 'HighlightCode',
    components: { prviewCode, formula, group },
    data() {
        return {
            code: `let msg = "hello world"
        console.log(msg)`,
            visible: false,
            groupVisible: false
        };
    },
    computed: {},
    mounted() {},
    methods: {
        handleFormula() {
            this.visible = true;
        },
        handleGroup() {
            this.groupVisible = true;
        }
    }
};
</script>
<style scoped></style>

# 6.prismjs 官网地址:https://prismjs.com/