13

I'm using Google autocomplete address form. I found example at google official web page. Everything is fine. Everything works! but it's native Javascript,

I have Vue application and I don't like how I change text input values from JS script. The idea is that when I change something in main input, JS event listener should change values for other inputs:

 document.getElementById(addressType).value = val;

Problem is that I should use "document" to change values:

 document.getElementById('street_number').value

I would like to have something like tat:

 <input type="text" v-model="input.address" ref="addressRef">

And to read values:

export default {
        data() {
            return {
                input: {
                    address: "",
                    ...
                }

            };
        },
        methods: {
            test() {
                console.log(this.input.address);
                console.log(this.$refs.addressRef);
        }
       }

So the question is:

  • How to set the value from JS code to update binding values? Right now values are null because I use "getElementById("id").value = val"

1 Answer 1

22

You can emit input event afterwards which v-model relies on for updating its value:

let el = document.getElementById("id");
el.value = val;
el.dispatchEvent(new Event('input'));

In action:

Vue.config.devtools = false

const app = new Vue({
  el: '#app',
  
  data: {
    message: null
  },
  
  methods: {
    updateBinding() {
      let el = document.getElementById("input");
      el.value = 'Hello!';    
      el.dispatchEvent(new Event('input'));
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="updateBinding">Click me </button><br>
  <input id="input" v-model="message" placeholder="edit me">
  <p>Message is: {{ message }}</p>
</div>

2
  • Looks it does not works in my example Can you help me please?
    – grep
    Jun 4, 2019 at 16:01
  • 2
    @grep new Event(addressType) should be new Event('input') Jun 4, 2019 at 16:11

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.