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

Viewed 2236

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>
1 Answers
Related