Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue submit button data

Suppose I had this code

<main>
    <form>
        <input type="text" v-model="name"> 
        <button type="submit" @click="submit">
            Submit From Vue Property
        </button>
    </form>
</main>

And this the Vue code.

new Vue({
   el : 'main',
   data : {
       name : ''
   },
   methods : {
      submit(){

      }
   }
}) 

how to submit to server from Vue data property instead? That i used in submit method.

( honestly, my actual code is much complicated but the problem is same. How to submit Vue data property instead? )

like image 444
iwgx Avatar asked Jul 30 '17 08:07

iwgx


2 Answers

If you are looking for an ajax based solution, consider using a library called 'axios'. It lets you post/get data using urls much like jquery's get and post methods.

To use axios you need to first install axios using npm, npm install axios --save, import it using import axios from axios and use this in submit. The new code will look like below:

<main>
    <form @submit.prevent="submit">
        <input type="text" v-model="name"> 
         <button type="submit">
            Submit From Vue Property
        </button>
    </form>
</main>


new Vue({
   el : 'main',
   data : {
       name : ''
   },
   methods : {
      submit(){
          axios.post('/your-url', {name: this.name})
          .then(res => {
              // do something with res
          })
          .catch(err => {// catch error});
      }
   }
})
like image 83
Shekhar Joshi Avatar answered Sep 21 '22 00:09

Shekhar Joshi


Here you can submit total formdata using vue variables.you can make api's using axios.

<template>
  <div>
    <form @submit.prevent="submitform">
       <input type="text" v-model="formdata.firstname"> 
       <input type="text" v-model="formdata.lastname"> 
       <input type="text" v-model="formdata.email"> 
       <input type="text" v-model="formdata.password"> 
       <button type="submit">
         Submitform
       </button>
    </form>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: 'el',
  data () {
    return {
       formdata:{ firstname: '', lastname: '', email: '', password: '' }
       // this is formdata object to store form values
    }
  },
  methods: {
    submitform(){
      axios.post('/url', { this.formdata })
      .then(res => {
         // response
      })
      .catch(err => { 
         // error 
      })
  },
  mounted () {

  },
  components: {

  }
}
</script>
like image 41
Bhaskararao Gummidi Avatar answered Sep 20 '22 00:09

Bhaskararao Gummidi