Search code examples
javascriptvue.jsvuejs2mathjax

Update dynamic MathJax with Vuejs 2?


P.S: Now i know how to fix this. bind data with v-html

   <div id="app">
    <h1 v-html="math"></h1>
    <button @click='change'>Change</button>
   </div>

var vm = new Vue({
  el: '#app',
  data: function() {
    return {
      math: '`sum`'
    }
  },
  methods : {
    change : function() {
      this.math = '`a '+Math.floor((Math.random() * 10) + 1)+'`';
this.$nextTick(function() {
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
       });

    }
  }
})

When i update data, it duplicate element ??? I dont know why, how to update MathJax with vuejs 2 ?

This is my app: Image

var vm = new Vue({
  el: '#app',
  data: function() {
    return {
      math: 'sum'
    }
  },
  methods : {
    change : function() {
      this.math = 'sum_'+Math.floor((Math.random() * 10) + 1);
this.$nextTick(function() {
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
       });

    }
  }
})

Solution

  • You could replace the entire contents of the MathDiv element and call MathJax.Hub.Typeset(), but there is a more efficient approach, which is to ask MathJax for the element jax for the mathematics, and call its method for replacing the formula shown by that element. So the updated code will look like:

      <div id="app">
       <h1 >{{ math }}</h1>
        <button @click='change'>Change</button>
      </div>
    
    
     <script>   
     var vm = new Vue({
          el: '#app',
          data: function() {
            return {
              math: '`sum_1`'
            }
          },
          mounted: function () {
            this.$nextTick(function () {
              MathJax.Hub.Typeset()    
            })  
          },
          methods : {
            change : function() {
              this.math = 'sum_'+Math.floor((Math.random() * 10) + 1);
              this.$nextTick(function() {
              var math = MathJax.Hub.getAllJax("MathDiv")[0];
                MathJax.Hub.Queue(["Text", math, this.math]);    
              });
            }
          }
        })
    </script>
    

    Refer: http://docs.mathjax.org/en/latest/advanced/typeset.html#manipulating-individual-math-elements

    OR

    You could use v-html to bind the data to the element.