Home > database >  How to fill the form with get request data?
How to fill the form with get request data?

Time:04-05

I made user information page and users can change and update their information. I want to display the data and fill form inputs automatically with get request data.

<div >
                  <div >
                    <label for="username">Username</label>
                    <input type="text"  id="username" placeholder="Username" v-model="username" disabled>
                  </div>
                </div>

Here is my methods:

methods:{

export default {
  name:'PPage',
  data(){
    return{
      isEditable:false,
      isHidden:false,
      username:"",
      userinfo:[]
    }
  },
  methods:{
    getProfile(){
      if(this.$route.params.id == undefined ||  this.$route.params.id == null){
        axios.get(`/v1/management/update_user/`)
            .then(res=>{console.log(res)
              this.username = res.data

            })
      }else {
        axios.get(`/v1/management/update_user/${this.$route.params.id}`)
            .then(res=>{console.log(res)
              this.username = res.data
            })
      }
    },
    
  mounted() {
    this.getProfile()
  }
}

here I get the data but its not the actual data.

CodePudding user response:

This kind of basic code should totally work

<template>
  <div>
    <div >
      <label for="username">Username</label>
      <input type="text"  id="username" placeholder="Username" :value="username" disabled>
      <button @click="fetchUser">fetch some user</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: 'nick'
    }
  },
  methods: {
    async fetchUser() {
      const response = await fetch('https://jsonplaceholder.typicode.com/users/1')
      const data = await response.json()
      this.username = data.username
    },
  }
}
</script>

Here is a playground.

CodePudding user response:

You can use v-model to bind the data into the form fields. For demo purpose instead of v-for, I am directly binding the value based on index.

Working Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      userInfo: []
    }
  },
  mounted() {
    this.getProfile();
  },
  methods: {
    // Just for demo I am directly assigning the mock response in userInfo array. You can replace that with API call response.
    getProfile() {
        this.userInfo = [{
        username: 'alpha'
      }]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  UserName : <input type="text" v-model="userInfo[0].username">
</div>

  • Related