vue 项目 将代码块实现高亮效果

转载出处

https://www.cnblogs.com/Jimc/p/13161836.html

1添加依赖

npm install highlight.js --save 或 yarn add highlight.js

2创建高亮样式文件 highlight.js

/**
 * 自定义代码高亮插件
 */
import hljs from 'highlight.js'
import 'highlight.js/styles/vs.css'

const install = function (Vue) {
    Vue.directive('highlight', {
        deep: true,
        bind (el, binding) {
            // on first bind, highlight all targets
            let targets = el.querySelectorAll('code')

            targets.forEach(target => {
                if (typeof binding.value === 'string') {
                    // if a value is directly assigned to the directive, use this
                    // instead of the element content.
                    target.textContent = binding.value
                }
                hljs.highlightBlock(target)
            })
        },
        componentUpdated (el, binding) {
            // after an update, re-fill the content and then highlight
            let targets = el.querySelectorAll('code')

            targets.forEach(target => {
                if (typeof binding.value === 'string') {
                    // if a value is directly assigned to the directive, use this
                    // instead of the element content.
                    target.textContent = binding.value
                    hljs.highlightBlock(target)
                }
            })
        },
    })

}

if (window.Vue) {
    window['highlight'] = highlight
    Vue.use(install) // eslint-disable-line
}

export default install

在src/main.js中引入:

// highlight.js代码高亮插件
import Highlight from ‘./directive/highlight’; // 这里是你项目highlight.js所在路径
Vue.use(Highlight);

使用

<!-- 1.如果你需要高亮的代码是一个变量值,那么你可以这样使用它。 其中 sourcecode 为变量。 
<pre v-highlight="sourcecode"><code></code></pre>
<!-- 2.如果你需要高亮的代码固定的源代码,那么你可以这样使用它。 -->
const s = new Date().toString()

效果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值