使用背景:
随着AI流行,各互联网公司都在开始研发AI相关的产品,比如:AI问答、AI写作、AI阅读等。一般是前端用Fetch 进行流式请求,返回markdown格式的数据,返回的内容不可避免的就会出现各种数学公式、Latex等公式,这时候Mathjax 库旧派上了用场。
//utils/mathjax.js
// @ts-nocheck
// mathJax全局配置文件
window.MathJax = {
tex: {
inlineMath: [
["$", "$"],
["\\(", "\\)"],
], // 行内公式选择符
displayMath: [
["$$", "$$"],
["\\[", "\\]"],
], // 段内公式选择符
},
startup: {
ready () {
MathJax.startup.defaultReady();
},
},
};
//main.js
import "@/utils/mathjax"; // 必须在引入mathjax前引入mathjax的配置文件
// import "mathjax/es5/tex-mml-chtml"; // 使用 tex-mml-chtml
import "mathjax/es5/tex-mml-svg"
//useRenderMath.js
import { nextTick } from 'vue'
function useRenderMath () {
nextTick(() => {
MathJax.texReset();
MathJax.typesetClear();
MathJax.typesetPromise().catch(err => {
console.log(err?.message)
});
})
}
export default useRenderMath
//index.vue
<script setup>
import renderMath from './useRenderMath'
const inner=ref('')
inner.value=`$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$`
renderMath()
</script>