Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined props in Vue js child component. But only in its script

I have just started using Vue and experienced some unexpected behavior. On passing props from a parent to child component, I was able to access the prop in the child's template, but not the child's script. However, when I used the v-if directive in the parents template (master div), I was able to access the prop in both the child script and child template. I would be grateful for some explanation here, is there a better was of structuring this code? See below code. Thanks.

Parent Component:

<template>
<div v-if="message">
<p>
{{ message.body }}
</p> 
<answers :message="message" ></answers>
</div>
</template>

<script>
  import Answers from './Answers';
  export default {
    components: {
      answers: Answers
    },
    data(){
      return {
        message:""
      }
    },
    created() {
      axios.get('/message/'+this.$route.params.id)
        .then(response => this.message = response.data.message);
    }
  }
</script>

Child Component

<template>
  <div class="">
  <h1>{{ message.id }}</h1> // works in both cases
  <ul>
    <li v-for="answer in answers" :key="answer.id">
      <span>{{ answer.body }}</span>      
    </li>
  </ul> 
  </div>
</template>

<script>
  export default{
    props:['message'],    
    data(){
      return {
        answers:[]
      }
    },    
    created(){
      axios.get('/answers/'+this.message.id) //only worls with v-if in parent template wrapper
        .then(response => this.answers = response.data.answers);
    }
  }
</script>
like image 404
paulc Avatar asked Oct 17 '22 10:10

paulc


1 Answers

this.message.id only works with v-if because sometimes message is not an object.

The call that you are making in your parent component that retrieves the message object is asynchronous. That means the call is not finished before your child component loads. So when your child component loads, message="". That is not an object with an id property. When message="" and you try to execute this.message.id you get an error because there is no id property of string.

You could continue to use v-if, which is probably best, or prevent the ajax call in your child component from executing when message is not an object while moving it to updated.

like image 189
Bert Avatar answered Oct 20 '22 16:10

Bert