首页 > 解决方案 > Passing time from my function to data() time: in vuejs

问题描述

I have this method function that show me the duration of audio file but i don't know how to pass the value from checkMp3SizeAndDuration of time to data() {return { time: '' } }

Here's the code:

data () { 
    return {    
      time: ''
    }
  },   

methods: {  
checkMp3SizeAndDuration () {  

      const files = document.getElementById('file').files
      const file = files[0] 
      const reader = new FileReader()
      const audio = document.createElement('audio')
     
      reader.onload = function (e) {
        audio.src = e.target.result 
        let time = '' 
        audio.onloadedmetadata = () => {
          const seconds  = audio.duration
          const duration = moment.duration(seconds, 'seconds') 
          const hours = duration.hours()
          if (hours > 0) { time = `${hours}:` } 
          time = `${ duration.minutes()  }:${duration.seconds()}`  
          console.log(time) <-- Example time log: 3:51
          this.time = time // Don't work here..
        } 
        audio.addEventListener('onerror', function () {
          alert('Cannot get duration of this file.')
        }, false)
      }  
      reader.readAsDataURL(file)  
    }
}

You can view the jsfiddle here: https://jsfiddle.net/xzktcrd2/

标签: javascriptfunctionvue.jsmethods

解决方案


我有两个你可以试试的东西:

1.把它放在你的函数的末尾:

this.time = *your value*

2在你的时间变量之后调用函数并在你的函数结束时返回你的值

data () { 
  return {    
    time: this.checkMp3SizeAndDuration();
  }
}, 

checkMp3SizeAndDuration () {  

  const files = document.getElementById('file').files
  const file = files[0] 
  const reader = new FileReader()
  const audio = document.createElement('audio')
 
  reader.onload = function (e) {
    audio.src = e.target.result 
    let time = '' 
    audio.onloadedmetadata = () => {
      const seconds  = audio.duration
      const duration = moment.duration(seconds, 'seconds') 
      const hours = duration.hours()
      if (hours > 0) { time = `${hours}:` } 
      time = `${ duration.minutes()  }:${duration.seconds()}`  
      console.log(time) <-- Example time log: 3:51
      this.time = time // Don't work here..
    } 
    audio.addEventListener('onerror', function () {
      alert('Cannot get duration of this file.')
    }, false)
  }  
  reader.readAsDataURL(file) 

  return *your value*
}

推荐阅读