Transferring time between functions in Vue.js: A journey from one function to another

Struggling to pass the value from checkMp3SizeAndDuration method function to data() {return { time: '' } }

Check out the code snippet below:

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 // Not working here..
        } 
        audio.addEventListener('onerror', function () {
          alert('Cannot get duration of this file.')
        }, false)
      }  
      reader.readAsDataURL(file)  
    }
}

Take a look at the jsfiddle for more details: https://jsfiddle.net/xzktcrd2/

Answer №1

Here are two suggestions you can try:

1. Add the following code snippet to the end of your function:

this.time = *your value*

2. Call the function after defining your time variable and return the value at the end of the function:

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 // Do not assign value here..
    } 
    audio.addEventListener('onerror', function () {
      alert('Cannot get duration of this file.')
    }, false)
  }  
  reader.readAsDataURL(file) 

return *your value*
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The compatibility between Laravel's @vite('resources/js/app.js') and the froala editor plugin seems to be causing issues

I have incorporated a Vue.js based commenting system and inbox messages system in my Laravel website. Additionally, I am utilizing a wysiwyg editor (Froala Editor) in my forms for uploading projects. The issue I am facing is that the Froala Editor does no ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

What is the best way to determine which watchers are triggered in Vue.js?

Within my parent component, there are numerous nested child components. Whenever a click occurs on one of the child components, it triggers an update to the route. The parent component watches the route property and performs certain actions when it change ...

My method for updating form input properties involves switching the disable attribute from "false" to "true" and vice versa

I have a form that uses Ajax to submit data. Once the user submits the form, the text is updated to indicate that the data was sent successfully, and then the form is displayed with the fields filled out. I want to display the form but prevent users from r ...

"NODEJS: Exploring the Concept of Key-Value Pairs in Object

I am facing a challenge with accessing nested key/value pairs in an object received through a webhook. The object in req.body looks like this: {"appId":"7HPEPVBTZGDCP","merchants":{"6RDH804A896K1":[{"objectId&qu ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...

How to eliminate the hash from a particular page in VueJS

My dilemma is quite similar to the one discussed in this Vue router thread on removing hash on certain pages I need to configure the hash mode for all pages except for mysite.com/success. This specific page is accessed via redirect from ...

How can JSON data be passed to the Google Charts API?

I am currently working on a project that involves retrieving JSON data from a website and visualizing it on a live graph using the Google Charts API. Despite my efforts, I am unable to get the chart to display properly. Can someone please guide me in the r ...

What is the best way to retrieve the local image path, transform it into a File object, and subsequently transfer it to firebase?

My current form includes a signup option where users can choose to upload a profile picture. In case they do not upload a profile picture, I aim to use a default one (think of the default Facebook profile picture). The image is imported as: import defaul ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Warning in Next.js: Each element in a list requires a distinct "key" property

Currently, I am in the process of building an e-commerce platform using Nextjs. My current focus is on enhancing the functionality of the myCart page, which serves as a dashboard for displaying the list of items that have been ordered. Below is the code s ...

Ways to extract the source code of a webpage that has been modified on load

While working on extracting data from a website (completely within legal boundaries), I encountered an interesting situation. This particular site has 5 questions with answers on each page. However, upon inspecting the source code by pressing Ctrl+U, I no ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...

Unable to invoke function from code-behind using PageMethods - error undefined

I am in the process of creating a website where users can customize their own cakes. Each cake comes with a base price and various options that may incur additional charges. These additional prices are stored in the database and can be retrieved using the ...

AngularJs promise is not resolved

Before processing any request, I always verify the user's authorization. Here is the factory code that handles this: (function() { angular.module('employeeApp').factory('authenticationFactory', authenticationFactory); fun ...

Arrays nested in Laravel validator responses

Is there a way to customize the validator responses to expand nested arrays in Laravel? By default, Laravel uses the "dot notation" for error messages like this: [ 'organisation.name' => 'required|max:60|min:3', ...

Steps for importing a React component as an embedded SVG image

I have developed a SVG component in React by converting an SVG file to a React component using the svg-to-react cli tool. In order to load and display additional svg files within this component, I am utilizing the SVG image tag as demonstrated below. This ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

Vuetify Upload Files

Recently, I implemented a form containing the Vuetify component v-file-input: <v-file-input chips multiple label="File(s)" v-model="file.files"></v-file-input> The structure of my data object is as follows: data: () => ({ file: { ...

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...