useMathJaxService.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {reactive, watch} from 'vue'
  2. import {createGlobalState} from "@vueuse/core";
  3. import config from "@/config";
  4. export const useMathJaxService = createGlobalState(() => {
  5. const MathJax = {
  6. tex: {
  7. inlineMath: [["$", "$"], ["\\(", "\\)"]], //行内公式选择符
  8. displayMath: [["$$", "$$"], ["\\[", "\\]"]], //段内公式选择符
  9. // autoload: {color: [], colorv2: ['color']}, // 3.0开始已经不支持此选项了
  10. packages: {'[+]': ['noerrors', 'mathtools', 'ams']}
  11. },
  12. options: {
  13. skipHtmlTags: ["script", "noscript", "style", "textarea", "pre", "code", "a"], //避开某些标签
  14. ignoreHtmlClass: 'tex2jax_ignore',
  15. processHtmlClass: 'tex2jax_process'
  16. },
  17. loader: {
  18. load: ['input/asciimath', '[tex]/noerrors', '[tex]/mathtools', '[tex]/ams']
  19. }
  20. }
  21. // NOTE:mathjax库在加载完毕后会用新对象直接覆盖window.MathJax, 所以后续都需要使用window.MathJax
  22. window.MathJax = MathJax
  23. const updateMathJax = function (el) {
  24. // 指定了HTML元素即更新指定元素,否则全部更新
  25. const elements = []
  26. if (el instanceof HTMLElement) elements.push(el)
  27. const mathjax = window.MathJax
  28. if (!mathjax.version) return
  29. mathjax.startup.promise.then(_ => mathjax.typesetPromise(elements))
  30. }
  31. const script = document.createElement('script')
  32. script.src = config.mathJaxCDN
  33. script.onload = () => updateMathJax()
  34. document.head.appendChild(script)
  35. return {
  36. MathJax,
  37. updateMathJax
  38. }
  39. })