5

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ah I see. Thanks for your explanation Bert thats cleared things up. Much appreciated. Will stick with the v-if directive on your advice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.