Invoke a function within one component using another component

I am facing an issue with deleting playlists displayed on my page. These playlists are fetched from an external API and each playlist has a delete button which is supposed to remove the playlist both from the API and the view.

The deletion process works smoothly for the API, but I am struggling to update the view after deleting a playlist.

Among my components is "Playlists.vue", where I have the following code:

<div class="playlists" v-if="playlists">
        <playlist v-for="playlist in playlists"
                  v-bind:key="playlist.id"
                  v-bind:playlist="playlist">
        </playlist>
        <span v-if="playlists.length === 0">No playlist found</span>
</div>

In the Playlists.vue file, a fetchData function fetches the data from the API like this:

 methods: {
      async fetchData() {
        const playlists = await api.getAllPlaylists();
      }
    }

Another component, Playlist.vue, renders a single playlist as follows:

<div class="row">
    <div class="col">
      <textarea v-model="playlist.name" v-on:blur="updatePlaylist"></textarea> 
      <button v-on:click="deletePlaylist(playlist.id)">Delete</button>
    </div>
  </div>

To update the playlist after a delete operation, I tried re-calling the fetchData function after each delete by importing the Playlists.js component like this:

 import playlists from './Playlists';

And then called the fetchData function within my delete function:

deletePlaylist(id) {
        playlist.deletePlaylist(id);
        playlists.fetchData();
},

However, I encountered the following error:

Uncaught TypeError: WEBPACK_IMPORTED_MODULE_2__Playlists.a.fetchData is not a function

I have explored other solutions but unable to find a way to call methods from Playlists.vue in Playlist.vue

Any suggestions for fixing this issue or perhaps a better solution?

Thank you!

Answer №1

A potential solution could involve utilizing a Mixin in your Vue application. By creating a global Mixin, you can ensure that certain functionality is available across all components.

Vue.mixin({
  methods: {
     async fetchData() {
       const playlists = await api.getAllPlaylists();
     }
  }
});

To implement this Mixin globally, place the code snippet before your main Vue instance declaration.

If you prefer to restrict the Mixin's scope to specific components only, define it separately as shown below:

var fetchData = {
  methods: {
     async fetchData() {
       const playlists = await api.getAllPlaylists();
     }
  }
}

You can then include this Mixin within individual component definitions like so:

  export default {
     mixins: [fetchData],
     data(){
        //...
     }
  }

For further information on using Mixins in Vue.js, refer to https://v2.vuejs.org/v2/guide/mixins.html

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

Activate a jQuery collapsible feature through an external hyperlink

Can we enable the expansion of a jQuery collapse by clicking on an external link? For instance, let's say we have a link on the home page that leads to another page. When the user clicks on this link from the home page, we want it to redirect to the i ...

The callback function in JavaScript seems to be missing without ever being executed

I have a SendMail function using nodemailer that successfully sends emails, but the callback function logging "mail sent" is not getting executed. Any suggestions on what might be causing this? var email = '<a href="/cdn-cgi/l/email-protection" cla ...

Utilizing a CSV file as a Map with D3 and JavaScript

After thorough research through JavaScript and D3 documentation, I have not been able to find a solution to my problem... Is it feasible to import a CSV file with the following format: header, header string1, string string2, string ... stringN, string an ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Acquire information asynchronously in JavaScript while inside a for loop

Recently, I've been exploring this particular function snippet: function add_cnh(arr_clelem){ var id=arr_clelem.getElementsByClassName("present")[0].id; var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date'); v ...

Obtain cell information when clicking on a specific field within a material-table

import MaterialTable from "material-table"; import ShipmentContext from "../context/ShipmentContext"; const ItemsTable: React.FC = () => { const shipmentcontext = useContext(ShipmentContext); const { filtered } = shipmentcontex ...

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

Tips for creating an onChange function in an input field using jQuery

I am looking to dynamically create inputs where each input has an `onChange` function with a variable. Here is my code: var distinct_inputs = 0; $('.icon1').click( function(){ distinct_inputs = distinct_inputs + 1 ; $('#insert-file&apo ...

Struggling to retrieve the session value using JavaScript in a C# application

Currently, I am attempting to retrieve four values from the session. However, I am only able to fetch two of them, while the other two seem to be missing. As a beginner, I apologize if my question comes across as too simplistic. Within a tree view, I have ...

Employ AJAX to dynamically refresh the page whenever a new row is inserted into the table

Currently, I am in the midst of learning AJAX because it is necessary for a project I am working on. The aim is to refresh a feed in real-time whenever a new row is added to a MYSQL table. While I have successfully achieved this using node.js, my client&ap ...

Using setState in an external function: A step-by-step guide

import Request from 'superagent'; const fetchApi = () => { let apiUrl = '/* URL */'; return Request.get(apiUrl).then((response) => { this.setState({ data: response.body }); }); } export d ...

What is the best way to implement collision detection using raycasting?

For my university project, I am looking to implement collision similar to what is shown in this example. However, I am facing an issue where collision is only working on the top of the object. I referred to this for guidance. My goal is to add collision to ...

Can you provide guidance on how to pass the selected value from a select option to an onchange function using Vue.js methods?

I'm facing an issue with passing the selected option value id from a select option to an onchange function in my methods. My goal is to store the selected value in the v-model "choosed" every time the user changes the select option, and then pass that ...

Unable to locate the Shadcn error module: Error encountered when trying to resolve the path '@/components/ui/accordion' within the directory 'Desktop/sadcn/src'

I'm encountering an issue with my Shadcn setup in a simple React app with TypeScript. The error message I'm getting is: Module not found: Error: Can't resolve '@/components/ui/accordion' in '/home/vinayak/Desktop/sadcn/src&ap ...

What is the alternative to using toPromise() when utilizing await with an Observable?

This website mentions that "toPromise is now deprecated! (RxJS 5.5+)", however, I have been utilizing it recently with AngularFire2 (specifically when only one result is needed) in the following manner: const bar = await this.afs.doc(`documentPath`).value ...

Achieving a smooth transition from a blur-out effect to a blur-in effect on a background Div

I created a blur in/out effect for my landing page, but it's not functioning as expected and I'm not sure why. It blurs out correctly, but the issue arises when I want the underlying Div to fade in. Currently, it just appears abruptly after the ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Update the input field's placeholder with the current date

Is it possible to dynamically set the placeholders for <input type='date' placeholder='{{ 'currentDate' }}'>? I have tried using the following variable: currentDate = this.datePipe.transform(new Date(), "yyyy-MM-dd& ...

Having trouble getting Node.js, express, socket.io, and ejs to work together?

Currently, I am working on improving my knowledge of java-script and had the idea to create a basic chat app using Express, stock.io, and ejs. Unfortunately, I am facing some challenges in getting it up and running smoothly. Below is the snippet from my ...

What is the best way to assign Reference Identification numbers to the orders?

Is there a way for me to obtain and attach the id reference to the order? I have retrieved the product and user ids. When I utilize my get method, it should retrieve all the details about the products and users. For instance, the data will display compreh ...