how to get a deep computed value

Viewed 233

i have this deep getter:

        getTotalVideoLength: {
            cache: false,
            get() {
                let duration = 0;

                _.forEach(this.videos, (video) => {
                    duration = duration + video.duration;
                });
    
                console.log(duration);
                
                return duration;
            }
        },

In the begin it logs undefined but after a few milliseconds it logs a number, but when i pass that 'getTotalVideoLength' as a prop to a child component it is always NaN.

Any help is welcome!

1 Answers

I'm thinking you may need to change your approach a bit. I'm sure you can make your code work with a computed property, but why force it with a hacky approach? Is there any reason why you need to use a computed value for this? What if you tried it with a data-property and method and called the method onMount to set the data-property so that you can guarantee that the values are already prepared before it's set? Try this code out and let me know how it works, please.

data() {
  totalVideoLength: 0,
},  
methods: {
  setTotalVideoLength(videos) {
    this.totalVideoLength = videos.reduce((accumulator, { duration }) => accumulator + duration, 0);
  },
},
onMount() {
 this.setTotalVideoLength(this.videos);
}

Related