Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js form submit did not get the new value of model-bind

Tags:

vue.js

I have a form

HTML:

<form ref="myForm" action="/AAA/BBB" method="get">
   <input type="text" hidden="hidden" v-model="myValue" name="myName" />
</form>
<button v-on:click="Send">Click me</button>

JS

new Vue({
   data: {
      myValue: 1
   },
   methods: {
      Send: function() {
         this.myValue = 2;
         this.$refs.myForm.submit();
      }
   }
})

When i click the button, it will send the value: 1

I'm sure that the value was modified before form submit

like image 604
Max Avatar asked Aug 28 '17 11:08

Max


People also ask

How to bind form input and textarea element values to Vue instance data?

We can bind form input and textarea element values to the Vue instance data using the v-model directive. According to the Vue docs, the v-model directive enables you to create two-way data bindings on form input, textarea, and select elements. It automatically picks the correct way to update the element based on the input type.

What is V-model in Vue JS?

What is v-model in Vue.js? One way to bind data in Vue.js is to use the v-model directive. When attached to an input, this model monitors the input and updates the given template once there is a change in the model. It also updates the data model if there is a change in the template. This is what we call two-way data binding.

What is data binding in Vue Vue?

Usually, you’ll be asked to enter your name to sign up. Then, after you subscribe to the newsletter, the name you provided will appear in the greeting of the email. This approach is called data binding. In this tutorial, we’ll explore the concept of form input binding in Vue and demonstrate the v-model directive on which it relies.

How to bind form inputs lazily in Vue JS?

Go to the component template and add the lazy property to all the v- model definitions in the inputs. When you run the app in your dev server, it should load the binding results lazily after you leave the tab. You should now have a basic understanding of form input binding in Vue JS.


1 Answers

When you set the value of a data property in a Vue instance's method, any elements bound with v-model will not update until the method has completed.

In your case, the bound input has not updated with the new value of myValue when you access the form and submit it.

To get around this, you can use the Vue.nextTick method, available on each Vue instance via this.$nextTick. This method allows you to pass a callback to execute once the Vue instance's template has finished updating.

In your case, you could do this:

Send: function() {
  this.myValue = 2;
  this.$nextTick(() => {
    this.$refs.myForm.submit();
  });
}
like image 167
thanksd Avatar answered Sep 20 '22 07:09

thanksd