javascript - 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/
解决方案
我有两个你可以试试的东西:
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*
}
推荐阅读
- c# - 将 C# 对象列表中的多行数据插入 Oracle 12 数据库中的表中
- mysql - 使用外键 ERROR 创建 MYSQL 表
- reactjs - 使用 create-react-app 构建企业级应用程序
- python - 使用 to_pickle 在循环中保存多个数据帧
- linux - Linux stdout 提取滚动视图之外的数据
- python - 你如何让一个字母保持一种颜色,而其余的保持另一种颜色?
- angular - 创建一个角度库并在我的角度项目中本地使用它
- routing - TYPO3 9 LTS - 路由中断 extbase 操作链接
- reactjs - 如何通过单击 Reactjs 中的图像打开页面?
- mysql - MySQL使用子字符串定位更新列值