Home > Mobile >  Dynamic JS result doesn't load in Vue.js
Dynamic JS result doesn't load in Vue.js

Time:02-23

I made a quote calculator in plain JS on Codepen, and was happy with the results.

Now, I'm trying to reuse this calculator - which worked fine - within my Vue.js project. But for some reason, the console hits me with this error, when I try to use the calculator:

enter image description here

I suspect it's the swap from plain JS to Vue that's messing something up, but could anyone here enligthen me as to what it is I'm overlooking?

Thanks in advance

 <form>
  <div >
   <input type="text" min="0" max="100" id="churnRate" onchange="CalculateEstimate();" />
   <input type="text" min="0" max="100" id="invoulentaryChurn" onchange="CalculateEstimate();" />
   <input type="text" id="contributionMargin" onchange="CalculateEstimate();" />
   <output id="output">0</output>
   <input id="customerNumber" type="range" value="0" min="0" max="3000" step="100" onchange="CalculateEstimate(); sliderChange(this.value);" />
   <div ></div>
  </div>
  <div id="result"></div>
</form>

hej

min far er en mand

<script>
 export default {
  name: "calculator",
  methods: {
    CalculateEstimate: function () {
      var b1 = parseInt(document.getElementById("churnRate").value);
      var b2 = parseInt(document.getElementById("invoulentaryChurn").value);
      var b3 = parseInt(document.getElementById("contributionMargin").value);
      var b4 = parseInt(document.getElementById("customerNumber").value);

      document.getElementById("result").innerHTML =
        (1 / (b1 / 100)) * b3 * (b4 * (b2 / 100)) * 12 * 0.5  
    },
  },
};
</script>

CodePudding user response:

The "onchange" attribute in the input tag cannot directly access a Vue method. Instead of onchange, use the v-on:change Event Handler to bind your inputs with your Vue methods. (More information about event handlers here: https://v2.vuejs.org/v2/guide/events.html?redirect=true)

Here's what you could write:

<input type="text" min="0" max="100" id="churnRate" v-on:change="CalculateEstimate()" />
<input type="text" min="0" max="100" id="invoulentaryChurn" v-on:change="CalculateEstimate()" />
<input type="text" id="contributionMargin" v-on:change="CalculateEstimate()" />

A shorthand version for v-on:change is @change. Both work the same.

Also it looks like your CalculateEstimate equation seems to be incomplete, just to let you know ;)

  • Related