Is it possible to Use Vuejs 2 to Update MathJax dynamically?

Just figured out how to resolve this issue. Simply bind the data using v-html

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

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

    }
  }
})

Why is the element duplicating when I update the data? Any idea on how to update MathJax with vuejs 2?

Check out my app here: Image

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

    }
  }
})

Answer №1

If you want to update the MathDiv element with a new formula without replacing its entire contents and then trigger MathJax.Hub.Typeset(), there is a more efficient method available. This involves requesting MathJax for the specific element jax related to the mathematical expression, and calling its function to update the displayed formula. Here's an example of how you can modify the code:

  <div id="app">
   <h1 >{{ math }}</h1>
    <button @click='modify'>Modify</button>
  </div>


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

Reference:

Alternatively, you can utilize v-html to bind the data directly to the element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Utilizing a try/catch block for validating a JSON file is ineffective

I'm attempting to verify if a received string is JSON and I experimented with the code below: try { JSON.parse(-10); // Also tried with "-10" }catch(e) { console.log('inside catch'); } Surprisingly, the code never enters the catch ...

The function chartobject-1.render() is returning an error message stating: "Unable to locate the specified container within the document. This issue is occurring in the

I've encountered an issue while trying to integrate FusionCharts into my Vue.js project. Every time I attempt to render the charts within my components, I consistently run into this error. Here's a snippet of one of the components: <template&g ...

Ways to handle a hidden element in Selenium Webdriver

Special features of this element:- <textarea id="txtSuffixTitle" class="form-control" tabindex="3" rows="2" placeholder="Suffix Title" name="txtSuffixTitle" maxlength="50" cols="20" style="display: none; visibility: hidden;">Suffix Title </text ...

Is the Messenger Bot ignoring random users?

I am facing an issue that I need help explaining. The bot works perfectly when I use it from my own Facebook account. However, when I ask others to use it, the bot does not respond to them, even though I have received a green tick on the pages_messaging a ...

Issue: The component series.line does not exist. Please ensure it is loaded before using it in Vue Echarts

I added the line component, but I'm still encountering issues. I set up my project using vue cli 3 and referred to this guide, but I can't locate the vue.config.js file in my project. Therefore, I manually created a vue.config.js and placed it in ...

Having difficulty using the forEach() method to loop through the array generated by my API

During my troubleshooting process with console.log/debugger, I discovered that I am encountering an issue when attempting to iterate over the API generated array in the addListItem function's forEach method call. Interestingly, the pokemonNameList ar ...

What is the best way to monitor different selections to keep track of their state?

In a certain scenario, a user is presented with three options: They can select the body_type of a car, the car_year it was manufactured, or the car_make. Initially, there is a state called carJson which contains a list of cars. "2": { " ...

JavaScript code to prevent user from entering phone number

I operate a booking platform similar to AirBnB where users communicate with each other through messages on the site. My goal is to prevent users from sharing telephone numbers and email addresses within these messages. Currently, I am implementing a meth ...

The server at localhost responds with a CANNOT GET/ error message

This is the code snippet I've been working on: const express = require('express'); const app = express(); const bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({extended: false})); app.use(bodyparser.json()); c ...

I'm curious about how the OAuth protocol handles the return of parameters after the # symbol in the oauth_callback

Implement the single sign-on feature in the project using the OAuth protocol. However, the project is being redirected by Vue's routing system and requires the ability to jump to a specific page after the '#' symbol in the URL. It seems that ...

"Change opacity smoothly with the FadeToggle feature for a

I have a question that might seem silly, but I can't quite figure it out. How can I extend the duration of the fade effect? window.switchIn = function() { $('.red').fadeToggle(function(){ $('.blue').fadeToggle(function() { ...

Having trouble with submitting the second stage of a multi-step form through Ajax technology

I'm currently tackling a multi-step form project using JavaScript, specifically focusing on submitting the second step of the form via Ajax. I've taken the initiative to create a distinct JavaScript file titled ajaxRequest.js to manage the Ajax r ...

The problem of heavy images not uploading persists when using Ajax/Jquery, as the FormData appears to

I have encountered an issue while running this code for images. It works perfectly for small images up to 2.5mb each, and the form is supposed to handle a maximum of 8 images. However, when I try to upload images larger than 4mb, or more than one such imag ...

Vue directive that automatically updates input when blurred

I am currently working on a directive that trims the value of an input when it loses focus: import { DirectiveOptions } from "vue"; const Autotrim: DirectiveOptions = { inserted(el) { if(!(el instanceof HTMLInputElement) && !(el insta ...

Running the JavaScript code on a webpage using Selenium WebDriver

I am currently in the process of creating an automated test for a website, and I am encountering some difficulty trying to execute a specific function within the site's code. Upon inspecting the developer tools, I have identified the function I need ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

Utilize an asynchronous method to upload files to Google Cloud Storage in a loop

I am new to using Javascript and have been working on a loop to upload images to Google Cloud Storage. While the image uploads correctly with this code, I'm facing an issue where the path (URL) is not being saved in the database AFTER the upload. I a ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...