Question:
How to convert VueJS 3 Axios data from parent to child?

Problem

When I pass the data from the Parent to Child Component I wonder why it is not sent empty. I wanted to perform Slug Operations, but I could not solve it in any way.


For example:

I want to capture the data coming from the Axios data in the child component and take the necessary actions for them, but it is said that this. initial slug value is empty in the child part, that is, at the beginning.


ParentComponent.Vue


<template>

 <div class="mx-auto flex flex-col">

  <div>

   <span>title:</span>

   <input type="text" v-model="title">

  </div>

  <div>

   <span>Slug:</span>

   <Child-component :title="title" :initial-slug="slug"/>

  </div>

 </div>

</template>

<script>

import ChildComponent from "./ChildComponent.vue";


export default {

 name: "Parent",

 data() {

  return {

   title: '',

   slug: ''

  }

 },

 components: {ChildComponent},

 async created() {

  await axios.get(`/categories/4/detail`)

   .then((response) => {

    this.title = response.data.title

    this.slug = response.data.slug

   })

 }

}

</script>


ChildComponent.Vue


<template>

 <input type="text" v-model="slug" @input="wasEdited=true">

</template>


<script>

import Slug from "slug";


Slug.defaults.modes['pretty'] = {};

export default {

 name: "Child",

 props: {

  title: {

   type: String,

   required: true

  },

  initialSlug: {

   type: String,

   required: true

  }

 },

 data() {

  return {

   slug: this.initialSlug,

   wasEdited: false,

  }

 },

 methods: {},

 mounted() {

  this.slug = this.initialSlug

 },

 created() {

  this.slug = this.initialSlug

 },

}

</script>


I want the data I send to be written to the slug value.


Solution

What you want to do is actually a simple process, you should watch it with a watch. We turn the initial Slug into a function and the incoming data is assigned to the desired slug value.


initialSlug: function () {

  this.slug = this.initialSlug

}


<template>

 <input type="text" v-model="slug" @input="wasEdited=true">

</template>


<script>

import Slug from "slug";


Slug.defaults.modes['pretty'] = {};

export default {

 name: "Child",

 props: {

  title: {

   type: String,

   required: true

  },

  initialSlug: {

   type: String,

   required: true

  }

 },

 data() {

  return {

   slug: '',

   wasEdited: false,

  }

 },

watch: {

  initialSlug: function () {

   this.slug = this.initialSlug

  }

 },

}

</script>


Suggested blog

>Create a project using Vue.js: Beginners Guide

>Authentication with Vue 3 and Firebase

>Plugins and Presets for Vuejs project

>Create a Vue.js application with CLI Services

>Create a project using Vue.js: Beginners Guide

>Create Vue.js application API


Nisha Patel

Nisha Patel

Submit
0 Answers