[Vuejs]-How to handle (for now) missing data?

0👍

You can use v-if and not render the div until data is loaded, like following:

var vm = new Vue({
  el: '#root',
  data: {
    message: {}
  },
  mounted () {
     var vm = this
     setTimeout(function(){
       vm.message = {'text' : 'Hello'}
     }, 400)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

<div id="root">
  <div v-if="message.text">
    <span>{{message.text}}</span>
    <span>world</span>
  </div>
</div>

If you know the structure of the message data, you can initialise it initially with empty string and dont need any v-if or other mechanism to prevent this error.

var vm = new Vue({
  el: '#root',
  data: {
    message: {
      text: ''
    }
  },
  mounted () {
     var vm = this
     setTimeout(function(){
       vm.message.text = 'Hello'
     }, 400)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

<div id="root">
  <div>
    <span>{{message.text}}</span>
    <span>world</span>
  </div>
</div>

0👍

You could just declare one variable called asyncData and update it when the data comes in, Vue won’t throw an error if the key doesn’t exist if you declare an empty object:

var vm = new Vue({
  el: '#app',
  data: {
    asyncData: {}
  }
});

Then as the data arrives you can just set it and force the Vue instance to re-render:

// Receive data
vm.asyncData['message'] = "Hello World!";
vm.$forceUpdate();

Here’s the JSFiddle: https://jsfiddle.net/tvzjsb7e/

Leave a comment