最近实现一个web界面显示日志的功能,发现highlight显示的代码段结构挺清晰。记录一下动态加载时候hljs不会编译丢失高亮效果。
链接: highlightjs官方网站
但是有个问题就是使用动态异步请求的取数据去渲染时候,只在渲染时候执行一次,发现hljs并没再次执行,去百度查了很多地方没一个答案是正确的,官方也没提供更新或者手动更新片段的函数,其中试过调用highlightAuto获取value值,这样会造成页面卡死,显然不可取,后面使用vue的 v-if进行模板判断,发现也不行,高亮不仅达不到效果,最外面似乎有个遮罩层挡住了。又使用了key属性让它在拿到数据强制更新,结果显然已经,这是目前唯一成功的方法。
在此文中使用的是指令模式,下面这个就是图片就是指令相关。
这是片段显示的区域,在获取数据之后调用key+=1就能让vue强制渲染该代码块的结构并正确执行应该执行的逻辑。/** diff比较 */
<!--
* Copyright ©
* #
* @author: zw
* @date: 2022-08-12
-->
<template>
<el-card class="rounded-none" style="height: calc(100vh - 142px); border: unset;" :body-style="{padding: 0, height: '100%'}">
<pre v-loading="loading" v-highlight :key="key" class="h-full overflow-y my-0">
<code class="sql pt-0" v-html="snippet" />
</pre>
</el-card>
</template>
<script>
import axios from "axios";
import { getToken } from '@/utils/auth'
export default {
name: 'patroInspection',
data() {
return {
snippet: '',
key: 0,
loading: true
};
},
mounted() {
this.loadSnippet()
},
methods: {
loadSnippet() {
this.loading = true;
const baseUrl = process.env.VUE_APP_BASE_API
axios({
url: baseUrl + '/maintain/inspection/execute',
method: 'get',
responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() }
}).then(res => {
res.data.text().then(t => {
this.snippet = t;
this.key += 1
this.loading = false;
});
}).catch(e => {
this.loading = false;
})
}
},
// End
}
</script>
<style lang="scss" scoped>
pre,
code {
background-color: #1e1e1e;
&::-webkit-scrollbar {
width: 6px;
height: 6px;
background-color: #1e1e1e;
}
&::-webkit-scrollbar-thumb {
background-color: #e5e7eb;
border-radius: 3px;
}
}
</style>
希望对大家有帮助
严谨转载
本文含有隐藏内容,请 开通VIP 后查看