0

I'm trying to add a new feature in a legacy application (built on jQuery) and would like to use Vue.js (v2.6.12) for that.

For example, I have two inputs, and I have a Vue component which displays some data based on the values inside the two inputs (let's say it adds them both). Like this:

Vue.component('output-component', {
  template: `<span> {{outputValue }} </span>`,
  computed: {
    outputValue: function() {
      let value_num1 = document.querySelector('#id_num1').value;
      let value_num2 = document.querySelector('#id_num2').value;
      // I want to access values of #id_num1 and #id_num2 here.
      return value_num1 + value_num2;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<input type="number" id="id_num1" name="num1" value="1">
<input type="number" id="id_num2" name="num2" value="2">

<output-component/>

Is it even possible to access the DOM values of the inputs this way? And if so, is the above component reactive to changes in the inputs ?

Is there some alternative technique to achieve the same ? (other than of course using jQuery to look for changes in the input and change the output value)

1 Answer 1

1

You need to manually add event listeners to inputs:

Vue.component('output-component', {
  template: `<span> {{outputValue }} </span>`,
  data() {
    return {
      outputValue: null
    }
  },
  methods: {
    recalculateOutputValue() {
      let value_num1 = document.querySelector('#id_num1').value;
      let value_num2 = document.querySelector('#id_num2').value;
      this.outputValue = parseInt(value_num1) + parseInt(value_num2);
    }
  },
  mounted() {
    this.recalculateOutputValue()
    document.querySelector('#id_num1').addEventListener('change', this.recalculateOutputValue);
    document.querySelector('#id_num2').addEventListener('change', this.recalculateOutputValue);
  },
  beforeDestroy() {
    document.querySelector('#id_num1').removeEventListener('change', this.recalculateOutputValue);
    document.querySelector('#id_num2').removeEventListener('change', this.recalculateOutputValue);
  }
});


new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<input type="number" id="id_num1" name="num1" value="1">
<input type="number" id="id_num2" name="num2" value="2">

<div id="app">
  <output-component/>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.