vue中使用MathJax 3.0简单步骤

前言

最近公司项目中需要用到Latex公式替代传统的图片加文字类题型展示,需要用到MathJax3.0,故特此记录

概述

MathJax是一款开源的JavaScript显示引擎,适用所有现代浏览器,使用MathJax可以方便的在浏览器中显示数学公式,不需要使用图片。

目前,MathJax可以解析Latex、MathML和ASCIIMathML的标记语言。

MathJax官网:https://www.mathjax.org/

MathJax文档:http://docs.mathjax.org/en/latest/

安装

1.引入

MathJax使用网络字体(大部分浏览器都支持)去产生高质量的排版,使其在所有分辨率都可缩放和显示。

字体资源较大,所以,通常推荐使用CDN网络分发进行加载。

在项目index.html入口文件引入,官方的建议是引入到</head>标签前

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="Ma thJax-script"></script>

注意:如果想将此JS下到本地是不行的,因为js中以相对路径引入了其他的js,可以将github整个包放到项目里再以相对路径引入

2.配置

创建一个js配置文件,如:globalVariable.js

let isMathjaxConfig = false // ⽤于标识是否配置
const initMathjaxConfig = () => {
    if (!window.MathJax) {
        return
    }
    window.MathJax = {
        tex: {
            inlineMath: [
                ['$', '$'],
                ['\\(', '\\)']
            ], // ⾏内公式选择符
            displayMath: [
                ['$$', '$$'],
                ['\\[', '\\]']
            ] // 段内公式选择符
        },
        chtml: {
            scale: 1,//缩放比例
        },
        options: {
            skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code',
                'a'], // 避开某些标签
            ignoreHtmlClass: 'tex2jax_ignore',
            processHtmlClass: 'tex2jax_process'
        }
    }
    isMathjaxConfig = true // 配置完成,改为true
}
const TypeSet = async function (elementId) {
    if (!window.MathJax) {
        return
    }
    window.MathJax.startup.promise = window.MathJax.startup.promise
        .then(() => {
            return window.MathJax.typesetPromise()
        })
        .catch((err) => console.log('Typeset failed: ' + err.message))
    return window.MathJax.startup.promise
}
export default {
    isMathjaxConfig,
    initMathjaxConfig,
    TypeSet
}

3.引入

在main.js引入刚才创建的js文件并注册

import globalVariable from '@/assets/js/globalVariable.js' 
Vue.prototype.globalVariable = globalVariable 

3.使用

在需要渲染的页面 mouted和updated周期内执行

    mounted() {
      window.addEventListener('scroll', this.handleScroll)
      if (this.globalVariable.isMathjaxConfig) {
        // 判断是否初始配置,若⽆则配置。
        this.globalVariable.initMathjaxConfig()
      }
      this.globalVariable.TypeSet()
    },
    updated() {
      if (this.globalVariable.isMathjaxConfig) {
        // 判断是否初始配置,若⽆则配置。
        this.globalVariable.initMathjaxConfig()
      }
      this.globalVariable.TypeSet()
    },
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容