Обновите математическое уравнение, используя MathLive и Vue - PullRequest
3 голосов
/ 19 марта 2019

Я изо всех сил пытался использовать Vue и MathLive для обработки набора случайных чисел и их квадратов.Функция программы - генерировать случайное целое число от 1 до 35, вычислять квадрат и набирать его с помощью MathLive.Есть две кнопки, которые добавляют одну к целому числу или создают другую случайную.У меня нет проблем с набором начального значения, но когда я создаю другое целое число или добавляю 1 на страницу, он никогда не набирает заново.Я пытаюсь реализовать эту программу как компонент в Vue.Вот мой MWE (только компонент):

<template lang="html">
  <div class="problem">
    <p id="math">$${{num}}^2 = {{square()}}$$</p>
    <button @click="addOne">Add One</button>
    <button @click="randomInt">Random Number</button>
  </div>
</template>

<script>
import math from 'mathjs'
import MathLive from 'mathlive'

export default {
  name: 'Problem',
  data: function () {
    return {
      num: math.randomInt(1,35)
    }
  },
  watch: {
    num: function () {
      console.log("Data changed");
      // this.renderMath();
    }
  },
  created: function () {
    console.log("Hello This is created!");
    this.renderMath();
  },
  beforeMount: function () {
    console.log("This is beforeMount");
  },
  mounted: function () {
    console.log("This is mounted!");
  },
  beforeUpdate: function () {
    console.log("This is beforeUpdate");
    this.renderMath();
  },
  methods: {
    addOne: function() {
      this.num++
    },
    randomInt: function () {
      this.num = math.randomInt(1,35)
    },
    square: function () {
      return this.num**2
    },
    renderMath: function (event) {
      this.$nextTick(function(){
        MathLive.renderMathInElement("math");
      })
    }
  }
}
</script>

<style lang="css" scoped>
@import url("../../node_modules/mathlive/dist/mathlive.core.css");
@import url("../../node_modules/mathlive/dist/mathlive.css");
p {
  color: white;
}
</style>

Редактировать: Чтобы уточнить, когда я загружаю страницу, начальное значение правильно набирается с использованием MathLive, как показано ниже: enter image description hereЗатем после того, как я нажму кнопку Добавить один или Случайное число , программа должна сгенерировать новое значение, вычислить его квадрат и обновить это значение на экране, как показано ниже: enter image description here

Ответы [ 2 ]

2 голосов
/ 30 марта 2019

Кажется, что манипулирование DOM в MathLive вступает в конфликт с виртуальным DOM Vue, не позволяя Vue исправлять DOM с помощью обновленного текстового узла.

Обходной путь - применить key, чтобы принудительно создать элемент MathLive p при изменении key. Мы могли бы использовать num в качестве клавиши, так как она меняется с каждым нажатием кнопки:

<p :key="num">...</p>

Текущий наблюдатель на num необходимо обновить, чтобы вызвать renderMath() для обновления элемента MathLive:

watch: {
  num() {
    this.renderMath();
  }
},

Вам также следует рассмотреть возможность сделать square() вычисляемым свойством для более эффективного рендеринга :

// script
computed: {
  square() {
    return this.num ** 2
  }
}
// template
<p :key="num">$${{num}}^2 = {{square}}$$</p>

Edit MathLive in Vue component

2 голосов
/ 19 марта 2019

Вам необходимо использовать vue.js computed properties

new Vue({
  name: 'Problem',
  data: function () {
    return {
      num: math.randomInt(1,35)
    }
  },
  watch: {
    num: function () {
      console.log("Data changed");
      this.renderMath();
    }
  },
  computed: {
     square: function () {
        return this.num**2;
     }
  },
  created: function () {
    console.log("Hello This is created!");
    this.renderMath();
  },
  beforeMount: function () {
    console.log("This is beforeMount");
  },
  mounted: function () {
    console.log("This is mounted!");
  },
  beforeUpdate: function () {
    console.log("This is beforeUpdate");
    //this.renderMath();
  },
  methods: {
    addOne: function() {
      this.num++
    },
    randomInt: function () {
      this.num = math.randomInt(1,35)
    },
    renderMath: function (event) {
      this.$nextTick(function(){
        MathLive.renderMathInElement("math");
      })
    }
  }
}).$mount("#app")
<script src="https://unpkg.com/mathjs/dist/math.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mathlive@0.26.0/dist/mathlive.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <span>$${{num}}^2 = {{square}}$$</span>
  <span id="math"></span>
  <button @click="addOne">Add One</button>
  <button @click="randomInt">Random Number</button>
</div>
...