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

instructions for creating a hover effect where one div vanishes when hovering over another div

Is there a way to make the line visible when hovering over my circular div? #line { display: none } <div id='circle'> <div id= 'line'> ...

Having trouble with parsing the .mjs module from Iconify in Vue 3 CLI project that utilizes the Composition API and TypeScript

Issue Update: After modifying the code from if(data.aliases?.[name2] !== void 0) to: if(data.aliases != null && data.aliases[name2] !== void 0) in the iconify .mjs file, I was able to resolve the error. However, this fix needs to be implemented in ...

What is the best way to add attachments to the clipboard in a Chrome extension?

One possible way to achieve this is by using the navigator.clipboard.write API, but keep in mind that this API is not available to background pages of Chrome extensions. A method I attempted involved creating a blob like this: let blobFinal = null; // ...

Sending PHP output data to jQuery

Trying to implement this code snippet /* Popup for notifications */ $(document).ready(function() { var $dialog = $('<div></div>') .html('message to be displayed') .dialog({ ...

Achieving different results by modifying an array within a forEach loop

I am currently working on a forEach() function that increments an array by one for each iteration. The problem I am facing is that whenever I try to display the value of the number variable in the browser's console, it only shows me the final state i ...

Having trouble with sending a JSON post request in Flask?

I have a setup where I am utilizing React to send form data to a Flask backend in JSON format. Here is an example of the code: add_new_user(e){ e.preventDefault() var user_details = {} user_details['fname'] = this.state.first_name user_d ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Having trouble retrieving data from the payload within vuex actions

I am currently utilizing Vuex for state management. Here is my store.js file: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); export const store = new Vuex.Store({ state: { loggedIn : false }, getters: {}, mutations: ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Is it necessary to release a new library version for non-functional updates?

As the maintainer of several JavaScript libraries, I often find myself needing to update dependencies that don't necessarily require any functional changes. This is especially true when my library is not impacted by a breaking change in one of its dep ...

a guide to presenting information in a horizontal layout within a single table using the Laravel framework and Vue.js

I have 2 tables: table 1 ________________ | name_id name | | 1 john | | 2 heaven | |_______________| table 2 _______________________ | id name_id product | | 1 1 bag | | 2 1 shoes | |______ ...

How to Modify the Data in a Dynamic Object within the Vuex Store in a Nuxt Application

Within my Vue/Nuxt project, I have implemented a form where users can add and update dynamic fields for calculating price offers. Upon loading the form, one field is created using the beforeMount lifecycle, with the option for users to add more fields as n ...

Import existing data from a pre-filled form - VueJS - Bootstrap-Vue

I'm facing an issue with a form that has linked selects. When one select is filled, the other select should also be filled with the corresponding code. However, when opening the modal with the field value, it fails to load the value. I suspect this mi ...

Sending a object as an argument to a function

Could someone please help me understand the purpose of passing an object as a function parameter? I have been trying to learn Next.js and they frequently use this method in their code. If anyone could provide a brief explanation of why this is done, it wo ...

As you scroll, this smooth marquee effect gently shimmers with each movement

I've been trying out this code to create a scrolling marquee text, but the issue is that after 7000 milliseconds it starts to jitter, which doesn't make the text look good. Any suggestions on how I can fix this problem? Let me know! <script ...

What steps should be taken to enable the "You and moderator can reply" feature in a bot when sending proactive messages to channels?

A project I am currently working on involves creating a bot that sends proactive messages to channels. The client has requested that I include options like No reply or You and moderator can reply with the messages posted by the bot proactively. Here is wh ...

Tips for sending multiple JSON objects using the ajax() method

As of now, I have successfully implemented a $.getJSON() call to fetch a JSON string from a specific URL. Here is the simplified code that is currently functioning well: $.getJSON("myURL",function(data){ var receivedJSON = data; }); The retrieved JSO ...

How can I remove the div container every time the submit button is clicked?

I am currently working on a form that is capturing values as shown below. <form role="form" id="calculate"> <div class="form-group"> <select class="form-control" id="paper"> < ...

What is the best way to incorporate the .top offset into a div's height calculation?

Looking to enhance the aesthetic of this blog by adjusting the height of the #content div to match that of the last article. This will allow the background image to repeat seamlessly along the vertical axis. I attempted the following code: $(document).re ...

Are you struggling with perplexing TypeScript error messages caused by a hyphen in the package name?

After creating a JavaScript/TypeScript library, my goal is for it to function as: A global variable when called from either JavaScript or TypeScript Accessible via RequireJS when called from either JavaScript or TypeScript Complete unit test coverage Th ...