Siempay
Siempay

Reputation: 1002

v-model on input that dynamically changes value by other script ?

I have two input that store lat and lng from google map script, if the user changes the marker's position => these two inputs get the lat and lng that the user pecked, so I wanna get the value of these two inputs, I tried v-model but it didnt work I actually noticed that the v-model will be fired only if I changed the value of these input by typing or pasting something in. Is there a way that I can get the value of these inputs (like on-change) to my Vue instance?

Upvotes: 2

Views: 3843

Answers (3)

Sergiu Sandrean
Sergiu Sandrean

Reputation: 541

To trigger Vue.js to read your input's value after it changes dynamically from an external script, you have to call:

document.querySelector('#element-id').dispatchEvent(new Event('input'))

on your element. This works on both <input> and <textarea> elements. For <select> elements you would have to call:

document.querySelector('#element-id').dispatchEvent(new Event('change'))

Upvotes: 9

Med
Med

Reputation: 2802

Watch your variables using watch properties:

HTML:

<div id="el">
  <form>
    <input v-model="foo">
    <input v-model="bar">
  </form>
  <p>{{ foo }}</p>
  <p>{{ bar }}</p>
</div> 

JS:

new Vue({
   el: "#el",
   data: {
       foo: '',
       bar: ''
   },
   watch: {
      foo: function(value) {
         this.foo = value
       },
      bar: function(value) {
         this.bar = value
      }
   }
});

Upvotes: 0

highFlyingSmurfs
highFlyingSmurfs

Reputation: 3039

You need to watch your two variables, and assign the value to the new one.

Upvotes: 0

Related Questions