1

I am trying to print out the name property of an object using Vue.

Here's what I tried {{ selectedTopic.name }}, this throws this error Uncaught TypeError: Cannot read property 'name' of null

If I print out {{ selectedTopic }} it will wait until that data is available and then display without errors.

Now I understand that the data I'm requesting is not available at that stage, but why is it throwing an error? Shouldn't it just wait until that data becomes available like it does for {{ selectedTopic }}?

Vue app

  var qaSuggest = new Vue({
    el: '#qa-suggest',
    data: {
      selectedTopic: null,
      profiles: []
    },
    mounted() {
      bus.$on("send-topic", selectedTopic => this.selectedTopic = selectedTopic);
    },
    updated(){
      axios.get('/vueprofiles').then(response => this.profiles = response.data);
      console.log('selectedTopic: ', this.selectedTopic.name);
    }
  });

HTML

<div id="qa-suggest">
    <ul class="list-unstyled">
        <li v-for="profile in profiles">
          <div class="clearfix" style="border-bottom: 1px solid #ddd; padding: 5px;">
        <div class="pull-left">
          <img :src="profile.picture" class="img-responsive" style="max-width: 60px; margin-right: 10px;">
        </div>
        <div class="pull-left">
          <p style="font-size: 12px; margin-bottom: 0;">{{ profile.category }} / {{ profile.subcategory }}</p>
          <p><strong>{{ profile.name }}</strong></p>
        </div>
      </div>
    </li>
</ul>

Topic: {{ selectedTopic.name }}
1
  • Thanks guys both answers work great :) Commented Mar 29, 2017 at 22:04

3 Answers 3

1

You'll get the same kind of error if that were put into a computed property. Vue just executes the JS code as-is without any kind of null-protection.

In your case, I would protect that part of the template with a v-if="selectedTopic", or just use null checking directly in the interpolation: {{ selectedTopic ? selectedTopic.name : 'No topic selected' }}.

You could also initialize it to a default value, like an empty object {}, but in my opinion this is flawed because selectedTopic is now non-null but in fact no actual topic is selected, which complicates the code.

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

Comments

1

It doesn't "wait" so much as understand that undefined should be an empty string. You could initialize selectedTopic with an empty object, and you would get the result you're looking for.

data: {
  selectedTopic: {},
  profiles: []
},

Comments

1

The error is because you can't access a property on an object that is null. Instead, you might try

{{ selectedTopic ? selectedTopic.name : '' }}

Comments

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.