What could be causing the icons to not render conditionally in this Vue 3 application?

I'm currently developing an audio player using Vue 3 and integrating it with the Napster API.

Project specifications

The player includes a mute/unmute button and the following method:

toggleMute() {
  this.player.muted = !this.player.muted;
}

const musicApp = {
  data() {
    return {
      player: new Audio(),
      trackCount: 0,
      tracks: []
    };
  },
  methods: {
    async getTracks() {
      try {
        const response = await axios
          .get(
            "https://api.napster.com/v2.1/tracks/top?apikey=ZTk2YjY4MjMtMDAzYy00MTg4LWE2MjYtZDIzNjJmMmM0YTdm"
          )
          .catch((error) => {
            console.log(error);
          });
        this.tracks = response;
        this.tracks = response.data.tracks;
      } catch (error) {
        console.log(error);
      }
    },
    nextTrack() {
      if (this.trackCount < this.tracks.length - 1) {
        this.trackCount++;
        this.setPlayerSource();
        this.playPause();
      }
    },
    prevTrack() {
      if (this.trackCount >= 1) {
        this.trackCount--;
        this.setPlayerSource();
        this.playPause();
      }
    },
    setPlayerSource() {
      this.player.src = this.tracks[this.trackCount].previewURL;
    },
    playPause() {
      if (this.player.paused) {
        this.player.play();
      } else {
        this.player.pause();
      }
    },
    toggleMute() {
      this.player.muted = !this.player.muted;
    }
  },
  async created() {
    await this.getTracks();
    this.setPlayerSource();
    this.playPause();
  },
  computed: {
    isPlaying() {
      return !this.player.paused;
    },
    isMuted() {
      return this.player.muted;
    }
  }
};

Vue.createApp(musicApp).mount("#audioPlayer");
...

Issue at hand

My goal is to dynamically change the volume icon based on whether the player is muted or not. To achieve this, I utilize the isMuted computed property in the template:

<span class="volume" @click="toggleMute">
  <i v-show="!isMuted" class="fa fa-volume-up"></i>
  <i v-show="isMuted" class="fa fa-volume-off"></i>
</span>

Although the player's mute/unmute functionality works correctly, the volume icon doesn't update accordingly.

What might be causing this issue?

Answer №1

To incorporate a muted property, you can modify the code to include:

toggleMute() {
  this.player.muted = !this.player.muted;
  this.muted = this.player.muted
}

Then, in the template, you can bind icons to that property as shown below:

const musicApp = {
  data() {
    return {
      player: new Audio(),
      trackCount: 0,
      tracks: [],
      muted: false
    };
  },
  methods: {
    // existing methods here
    toggleMute() {
      this.player.muted = !this.player.muted;
      this.muted = this.player.muted
    }
  },
  async created() {
    await this.getTracks();
    this.setPlayerSource();
    this.playPause();
  },
  computed: {
    isPlaying() {
      return !this.player.paused;
    },
  }
};

Vue.createApp(musicApp).mount("#audioPlayer");
// CSS styles here
// External libraries and additional scripts
<HTML content with Vue bindings>

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

Tips on utilizing the ternary operator when binding in Vue

<label class="switch"> <input type="checkbox" v-on:change="updateRequiredData(list.input_permission_id,selected, selected == 'Applicant' ? list.status : selected =='Guaranter' ? list.guaranter_required : selected ='Refer ...

While the React Router URL is functioning correctly, the corresponding component is not

I am experiencing an issue where React Router is changing the URL but the component is not being updated. I have tried various solutions from StackOverflow, however, none of them seem to work for me. Below is the code I am working with: App.js: function Ap ...

WebVTT captions on a Chromecast receiver as the default option

Trying to set up closed captions for chromecast using the default Chrome sender app but it's not working. The code is similar to the sample provided in the docs, seen here. I've shared a snippet that might be too sandboxed, view it on a normal ht ...

Functionality of setExtremes ceases to function post initial loading

Initially, the setExtremes function works fine for the chart. However, when I switch pages or reopen the chart with a new JSON file, the setExtremes function stops working and fails to update the min and max values. Any idea why this could be happening? yA ...

Using subqueries in a node.js application can yield varying results, with success not always

In my Node.js query, I have encountered a strange issue where sometimes it works perfectly fine. The scenario involves inserting a club first and then inserting players in a second query. There's a subquery that retrieves the last inserted ID of the A ...

Is there a way to link the req.session.user from express-session to a chai-http request?

When it comes to my API, it relies on the express-session module for authentication. Each request is verified based on whether the req.session.user object exists within the request. The implementation can be seen in the snippet below: app.use(function(req ...

NextJS: Issue: Accessing a client module from a server component is not allowed. The imported name must be passed through instead

My current NextJS setup is structured as shown below: app/page.js 'use client'; import React from 'react'; export default function Home() { return (<div>Testing</div>); } app/layout.js export const metadata = { title ...

Is the first pageYOffset value on Android saved in cache?

Just discovered a small bug/feature with the Android browser. If you scroll the page down and then reload it, the window.pageYOffset value will not be equal to 0! Here's a simple example: http://pastebin.com/bHzc5Ymi To reproduce: ...

Learn how to implement language switching on your Vue.js 3 website using the <option> tag along with i18n functionalities

I am currently working on a Vue 3 project and I am looking to implement localization. I have successfully installed "vue-i18n": "^9.2.2" and added the following code to my main.js file: import { createI18n } from 'vue-i18n' const i18n = create ...

Sharing an Angular scope variable with JavaScript

I have a streetName variable within an Angular scope. <script type="text/javascript"> angular.module('addApp').controller('add', ['$scope',function($scope) { $scope.streetName = "Bonita Ln"; }]); < ...

Looping through the ajax data to populate ion-item elements

I am currently working on a loop that retrieves user IDs, names, etc. from a JSON file. I am trying to display this data in a list view within an Ionic framework. When I simply use direct alerts in JavaScript, the users are displayed correctly, but when I ...

Error: Attempting to access the 'findAll' property of an undefined value in the context of MariaDB and ExpressJs

TypeError: Cannot read property 'findAll' of undefined findAll function is causing an error, however the Connection was successful. Also, a database named managers has been created. app.js models index.js maria manager.model.js bin ww ...

Validate each element in the looped over input field and update the status for each element

I am currently developing a Vue component and have implemented a v-for loop in the HTML to generate v-text-fields. My goal is to validate that the input in each v-text-field matches one of the elements in an answer array. The current setup is as follows: & ...

PHP Temp File Not Found After AJAX File Upload

Recently, I've been researching how to upload files through AJAX using FormData and FileReader. However, I keep encountering a recurring issue. After initiating the file upload process, the file is sent to a PHP script for validation and then an atte ...

Issue with alignment in the multiselect filter of a React data grid

In React Data Grid, there is a issue where selecting multiple filter options messes up the column headers. Is there a solution to display selected filter options above a line in a dropdown rather than adding them to the column header? The column header siz ...

How to filter jQuery DataTables by column using comparison operators

Recently, I've been utilizing the amazing DataTables jQuery plugin along with the filter plug in. But now, I find myself pondering if there's a way to filter table columns by row using a comparison operator (such as '<', '>&a ...

Avoid or alter the alert stating that your modifications may not be saved

I am faced with the challenge of automatically logging a user out of an application after a period of inactivity. The issue arises when attempting to log the user out, as the browser triggers a 'Are you sure you want to leave' prompt when change ...

The JavaScript API for YouTube - when the state changes

I am facing a challenge while trying to embed a YouTube video onto one of our customer's websites. The requirement is for the video to display an image once it has finished playing. My initial approach was to remove the containing div so that an under ...

404 error occurs when Node.js cannot locate the public CSS files

Currently, I am encountering an issue while trying to serve public CSS files to a specific URL in my node.js project. The problem arises when the URL is set to 127.0.0.1/project/idProject as it attempts to fetch the CSS file from 127.0.0.1/project/css/styl ...

How exactly does this JavaScript code determine the index of the maximum value within an array?

Examining the specific line of code: let largest = arr.reduce((a,v,i) => v > a[1] ? [i,v] : a, [-1,0]); I find this part a, [-1,0] particularly perplexing, as I am unsure of its syntax. How does a function before the comma? ...