Search code examples
formsvue.jsvue-componentassign

How to prefill data in vue form?


I am using vue form to edit one item, but I cannot conclude in which method should I assign a values to categoryName and description to make those values ​​appear in form?

I tried to make axios call and assign response to categoryName and description in the methods: created, mounted, beforeMouned, but it does not show values of categoryName and description in input fields, although values are obtained from the backend. Also v-model.lazy does not give results.

This is my code:

<template>
  <div class="pt-5">
    <form @submit.prevent="submitCategory">
      <div class="form-group">
        <label for="categoryName">Category name</label>
        <input v-model.lazy="categoryName" value="categoryName" type="text" class="form-control" id="categoryName" aria-describedby="categoryNameHelp" placeholder="Enter category name">
      </div>
      <br>
      <div class="form-group">
        <label for="description">Description</label>
        <input v-model="description" type="text" class="form-control" id="description" placeholder="Enter description">
      </div>
        <br>
      <button type="submit" class="btn btn-primary mt-2">Submit</button>
    </form>
  </div>
</template>

<script>
export default {
  name: "EditCategory",
  data() {
    return {
      categoryName: '',
      description: '',
    }
  },
  beforeMount () {
    this.$axios.get(`/api/categories/${this.$route.params.id}`,{
        id: this.$route.params.id
      }).then((response) => {
      console.log(response.data)
      this.categoryName = response.categoryName;
      this.description = response.description;
    });    },
  methods: {
    submitCategory() {
      this.$axios.post('/api/categories', {
        categoryName: this.categoryName,
        description: this.description,
      }).then(response => {
        console.log(response)
        this.$router.push({name: 'Categories'});
      })
    },   
    initialize () {
     
     },

  },
}
</script>

<style scoped>

</style>

Solution

  • Axios Response object

    When we send a request to a server, it returns a response. The Axios response object consists of:

    1. data - the payload returned from the server
    2. status - the HTTP code returned from the server
    3. headers - headers sent by server

    You did console.log(response.data) in BeforeMount Hook. You will get your required data under response.data object

    this.categoryName = response.data.categoryName;
    this.description = response.data.description;