第一步 在public index.js中引入 mathjax
<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"></script>
第二步 创建 mathjax.js 文件
let isMathjaxConfig = false
const initMathjaxConfig = () => {
if (!window.MathJax) {
return
}
window.MathJax.Hub.Config({
showProcessingMessages: false,
messageStyle: 'none',
jax: ['input/TeX', 'output/HTML-CSS'],
tex2jax: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code', 'a']
},
'HTML-CSS': {
availableFonts: ['STIX', 'TeX'],
showMathMenu: false
}
})
isMathjaxConfig = true
}
const MathQueue = function (elementId) {
if (!window.MathJax) {
return
}
window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, document.getElementsByClassName(elementId)])
window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, document.getElementById(elementId)])
}
export default {
isMathjaxConfig,
initMathjaxConfig,
MathQueue
}
第三步 在main.js 中引入
import MathJax from './MathJax.js'
Vue.prototype.MathJax = MathJax
第四步 创建可复用的子组件 gs.vue
<template>
<div class="latexDiv" v-html="'$$'+latex+'$$'" />
</template>
<script>
import MathJax from '@/MathJax.js'
export default {
name: 'TheLatex2Math',
props: { latex: { type: String, default: '' }},
watch: {
latex() {
this.mathJax()
}
},
created() {
this.mathJax()
},
methods: {
mathJax () {
this.$nextTick(function () {
if (MathJax.isMathjaxConfig) {
MathJax.initMathjaxConfig()
}
MathJax.MathQueue('latexDiv')
})
}
}
}
</script>
第五步 引入使用
<template>
<div class="flex-item">
<TheLatex2Math :latex="gs" />
</div>
</template>
import TheLatex2Math from './gs.vue'
export default {
components: {
TheLatex2Math
},
data(){
return {
gs: 'P_{待估} = \\frac{1/a}{1/a+1/b+1/c}*P_A+\\frac{1/b}{1/a+1/b+1/c}*P_B+\\frac{1/c}{1/a+1/b+1/c}*P_C',
}
}
}
效果展示
注意点: 由于动态赋值latex写法中单斜杠会不能识别,所以转为双斜杠