Home > Mobile >  Vue: TypeError: Cannot read properties of undefined (reading 'title') on page reload
Vue: TypeError: Cannot read properties of undefined (reading 'title') on page reload

Time:03-05

I have a pretty common issue accessing data while the page is loading, however, I cannot figure this out.

My code is as follows:

    computed: {

       nowPlaying() {
               if(this.$store.state.radio && !this.loading) {
            
        let meta = Object.values(this.apollo).filter(el => el.channel === this.activeChannel)
          this.title = meta[0].title,
          this.artist = meta[0].artist
            }  
        },

Hot reload works as expected but page reload returns an undefined error for both title & artist:

TypeError: Cannot read properties of undefined (reading 'title') at VueComponent.nowPlaying (Player.vue?7cf3:45:1)

This happens only if I try to access an element in the meta array using [].

CodePudding user response:

Looks like on page load, this.apollo or this.activeChannel not available as computed property always call prior to mounted() hook.

Can you please ensure that this.apollo and this.activeChannel is available in mounted() or data property.

Demo how it works :

new Vue({
  el: '#app',
  data() {
    return {
      property: 'Example property'
    }
  },
  computed: {
    propertyComputed() {
      console.log('computed'); // Called first on page load
    }
  },
  mounted() {
    console.log('mounted');
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>{{ propertyComputed }}</div>
</div>

  • Related