Vue fails to reflect changes in data when it is updated

I have a page where I can access data by calling domain.com/subpage?soundfile=something

Using the fetch method, I extract the query parameter from the URL to retrieve the necessary information. The retrieval process is successful as indicated by the data being stored in this.recording. However, despite the console.log showing that everything is working correctly, neither my audio element nor the span component get updated. Why is this happening?

<template>
  <div>
    <audio controls>
      <source :key="key" :src="recording" type="audio/mp3" />
    </audio>
    <span :key="key">{{ recording }}</span>
  </div>
</template>

<script>
const axios = require("axios").default;

export default {
  data() {
    return {
      key: 0,
      recording: ""
    };
  },
  async fetch(context) {
    const ip = await axios.get(
      "somebackend/?soundfile=" + context.query.soundfile
    );

    this.recording = ip.data[0].file.url;
    console.log(this.recording); // gives me the correct url/mp3 file
    this.key++; // should update the audio element and the span but doesn't
  }
};
</script>

Answer №1

Resolved the issue by switching to asyncData instead of fetch method.

<template>
  <div>
    <audio controls>
      <source :src="audiofile" type="audio/mp3" />
    </audio>
    <span>{{ audiofile }}</span>
  </div>
</template>

<script>
const axios = require("axios").default;

export default {
  async asyncData(context) {
    const data = await axios.get(
      "backend-url/?audiofile=" + context.query.audiofile
    );

    return {
      audiofile: data.data[0].file.url
    };
  }
};
</script>

Answer №2

In order to notify the audio tag that the loading process has been completed, you must make sure to do so.

If you're not familiar with nuxt but have experience with vue, you can handle changes in recording by calling .load() on the audio tag.

For instance:

<audio controls ref='player'>
this.$watch('record', () => {
                this.$refs.player.load()
            })

Answer №3

One important detail that seems to have been overlooked is including the methods block:

export default {
  data() {
    return {
      id: 0,
      value: ""
    };
  },
  methods: {
    async getData(context) {
      const result = await axios.get(
        "backend/?data=" + context.query.data
      );
      this.value = result.data[0].url;
      console.log(this.value); // displays correct URL/file
      this.id++; // is supposed to update the audio element and span, but isn’t doing so
    }
  },
};
</script>

The issue arises from the absence of the methods block, causing a discrepancy with the expected reference to this, which should be the Vue instance. Consequently, the ID fails to update and although logged to the console, changes are not reflected in the template.

Best regards,

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

When utilizing the array.push method, new elements are successfully added, however, it appears to also overwrite the last object

I'm encountering a strange issue where every time I push an object to the array, the array's length increases as expected. However, the object that I push last ends up overriding all other objects. I can't seem to figure out my mistake, so p ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...

Implementing a confirmation dialog for POST requests in Flask

My first experience with Flask involves adding a confirmation dialog to a form, but only under specific conditions. Unfortunately, I'm unable to achieve this on the client side. While I was successful in implementing it for GET requests, POST requests ...

The Material UI autocomplete unexpectedly closes on click instead of displaying a popover as intended

I'm facing a challenge with adding a button to the Material UI autocomplete using the renderOption prop. I added a button to each row that was intended to display a PopOver component, but when clicking on the button, it automatically closes the autoco ...

I'm looking to customize my d3.js Bar Graph by changing the color of each bar individually and adding a Scale for them. How can I

I am currently working on constructing a graph that illustrates the data for the Amount of Resources utilized Per Project by creating a bar graph. I am aiming to customize the colors of the bars so that each one has its own unique color. Currently, the col ...

Unable to receive comment reply through Ajax without refreshing the comment section

I'm facing an issue where I cannot retrieve comment replies via Ajax under comments, even though the replies are successfully saved in the database. Oddly enough, upon refreshing the Index.php page, the replies display correctly. I suspect the problem ...

Choose an option using jQuery with the ability to navigate to the previous or next

I encountered a bug when I tried to click the next or previous button. Below is the HTML code snippet: $("#nextPage").click(function() { $('#pagination option:selected').next().attr('selected', 'selected'); console.log( ...

Unable to retrieve Java variable in JavaScript

Seeking guidance on how to retrieve Json data stored in a Java variable using JavaScript. Instead of accessing the data, the html source is displayed. Java: Gson gson = new Gson(); String json = gson.toJson(obj); request.setAttribute("gsonData", gson) ...

Developing a sliding menu with AngularJS

Currently, I am developing an AngularJS application. One of the features I am working on involves having a menu at the top of my page that, when an item is selected, will slide down to reveal content specific to that selection in the same area as the menu. ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Is there a way to verify that all of my HTML elements have been loaded in AngularJS?

I am currently utilizing angularJS version 1.2.1 along with angular-ui-bootstrap. Within my code, I have a collection of <ng-includes> tags from angularjs and <accordion> components from angular-ui. When loading the content, I need to initiat ...

What is the best way to display the data model in Angular as HTML?

I am facing an issue with my data-model where it needs to be converted or displayed as HTML, but currently it is only appearing as plain text. Here is the HTML code snippet: <div ng-repeat="item in ornamentFigures" class="ornament-item"> <la ...

How can I configure Vue 2 using Vue CLI to access and utilize images stored in the src/static directory?

I'm in the process of bundling my Vue CLI application to include src/static/xyz.png so that I can easily reference it as /static/xyz.png. Unfortunately, the documentation provided by Vue doesn't offer clear instructions on how to achieve this. I ...

Using jQuery to combine the values of text inputs and checkboxes into a single array or string

I need to combine three different types of items into a single comma-separated string or array, which I plan to use later in a URL. Is there a way to merge these three types of data together into one string or array? An existing POST string User input f ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

Sorting through a list post a retrieval action

Could you guys please help me understand why my code is not functioning properly? I am receiving an array from my backend rails API, which is providing the data correctly. I have created an empty array where I filter the records based on their ID. The fi ...

Unmounting a Vue3 component in the script setup: A step-by-step guide

Let's say we have a component structured like this. <template> <el-card @click='destroyCard'> ...... </el-card> </template> <script setup> ...... let destroyCard = () => { ...... } onUnmoun ...

Executing filepicker.io Javascript API calls may lead to unsafe errors in Javascript

I am currently using AngularJS and encountering an issue when trying to call filePicker.pickAndStore from my Upload controller. Every attempt to use a filepicker.io API function triggers an "Unsafe Javascript attempt" error: The frame requesting access ...

Difficulty encountered while implementing Ajax POST in CodeIgniter

I've been working on a project similar to a ticket system that occasionally requires lengthy answers. When using CKEDITOR in the answer area, the agent's changes are automatically saved to the database using Json GET. However, I encountered an er ...

What steps can I take to decrease the padding of this footer?

Is there a way to reduce the height of the footer so it doesn't dominate the screen on both large and small devices? https://i.sstatic.net/nIQz6.png import { Container, Box, Grid } from "@material-ui/core"; const Footer = (props) => { ...