vue2 集成prismjs

巫培
2023-12-01

vue2 集成prismjs

1.下载

npm install prismjs -S
npm install babel-plugin-prismjs -D

2.配置

  • babel.config.js

    module.exports = {
        presets: ['@vue/app'],
        plugins: [
            [
                'prismjs',
                {
                    languages: ['javascript', 'css', 'markup'],
                    plugins: ['line-numbers'], //配置显示行号插件
                    theme: 'solarizedlight', //主体名称
                    css: true
                }
            ]
        ]
    };
    
    
  • .babelrc 注意使用双引号,否则报错

    //.babelrc文件配置后的plugins选项内容
    "plugins": ["transform-vue-jsx", "transform-runtime", [
          "component",
          {
            "libraryName": "element-ui",
            "styleLibraryName": "theme-chalk"
          }
        ],
        ["prismjs", {
          "languages": ["javascript", "css", "markup"],
          "plugins": ["line-numbers"],
          "theme": "twilight",
          "css": true
        }]
      ]
    
    

3.封装

<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>

4.使用

<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>

 类似资料: