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

Why is TypeScript unable to recognize package exports? (using CommonJS as the module system and Node as the module resolution)

I have an NPM package that is built for ESM and CJS formats. The package has a dist folder in the root directory, which contains: dist/esm - modules with ESM dist/cjs - modules with CJS dist/types - typings for all modules In the package.json file, there ...

Error message: The Modelviewer is unable to load the local file, displaying the message "Unauthorized to access local resource."

For my WebAR project, I am utilizing Google's ModelViewer. In my vue.js project, I have a component that loads the model using the <model-viewer> attribute. My goal is to set the src attribute of the model-viewer to the absolute path of the .gl ...

What is the process for exporting an SVG file from a web page?

<svg class="paint" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect class="svgobject" x="458" y="165.28750610351562" width="142" height="56" fill="black" stroke="black" id="154" transform="translate(0,0)"> </rect> </svg> ...

"Unlocking the power of AngularJS translate: A step-by-step

I'm seeking answers to two questions. 1) How can I utilize angularjs translate with ng-repeat? Although my Json file works fine, the text does not display when using ng-repeat. Here is a snippet from my json: "rules":{ "points":[ {"t ...

Generate pre-set components using fundamental building blocks

Can I predefine some props for components? In my Vuetify example, let's say I want to customize the v-btn component with specific props. This custom implementation would act as a child component while still providing all the functionalities of the par ...

Display a text field when the onclick event is triggered within a for

Control Panel for($i = 1; $i <= $quantity; $i++){ $data .= '<b style="margin-left:10px;">User ' . $i . '</b>'; $data .= '<div class="form-group" style="padding-top:10px;">'; $data .= ' ...

What are the steps to refreshing a table using AJAX?

Struggling to update a table from my database, I have been following a PHP guide but can't get it to work. In a separate file, the data is retrieved and displayed in a table. I am attempting to use JavaScript to refresh this file. This code snippet ...

Create a project using Next.js and integrate it with the tailwindcss framework

My application utilizes TailwindCSS and NextJs. I am facing an issue where certain classes are not working after running npm run start, following a successful run of npm run dev. For example, the classes h-20 / text-white are not functioning as expected, w ...

Encountering a [$injector:modulerr] error while attempting to include modules in ZURB Foundation for Apps

I am currently working on a project that involves specific authentication which is functioning well in Ionic. My task now is to incorporate the same authentication system into the admin panel exclusively for web devices. I have already completed the instal ...

Is there a way to switch (transpose) the rows and columns of a dynamically generated HTML table from Highchair in Angular 12?

Click here to view the code for creating a highchart table. In the provided example, I have successfully implemented a highchart table using the code below. Highcharts.chart('container', { title: { text: 'Solar Employment Growth by Sec ...

Wrapping a group of elements with opening and closing tags using jQuery

I have a collection of distinct elements, like so: <section class="box-1"></section> <section class="box-2"></section> <section class="box-3"></section> My objective is to enclose all three elements within a div with a ...

Updating the HTML class with JavaScript

My HTML class has two classes $(document).ready(function() { $(".container").hover(function() { $('.green').addClass('display-on'); }); $(".container").mouseleave(function() { $('.black&apos ...

Using JavaScript, concatenate text from each line using a specified delimiter, then add this new text to an unordered list element

I am looking to extract text from named spans in an unordered list, combine them with a '|' separating each word within the same line, and append them to another ul. Although my code successfully joins all the words together, I'm struggling ...

Passing arrays to a Vue component in a static manner

I am trying to pass an array statically to my Vue component named ajax-table. After struggling to find a solution, I decided to use the following approach: <ajax-table header-names="Code, Name, Description, Type" field-names="code, name, descri ...

Struggling to retrieve Json data through Ajax in Rails 5

Hey there! I'm currently exploring the world of Rails action controllers with Ajax, and I've run into a bit of a snag. I can't seem to retrieve Json data and display it in my console.log using my Ajax function. The GET method works perfectly ...

Angular Leaflet area selection feature

Having an issue with the leaflet-area-select plugin in my Angular9 project. Whenever I try to call this.map.selectArea, VSCode gives me an error saying that property 'selectArea' does not exist on type 'Map'. How can I resolve this? I& ...

Algorithm that continuously increases a given date by 3 months until it surpasses or matches the specified creation date

I am currently working with QuickBase, a platform that involves HTML. My goal is to develop a code that can take a [fixed date] (always in the past) and increment it by 3 months until the MM/YYYY exceeds or equals the MM/YYYY of the [creation date]. Once t ...

Begin Leaflet with JQuery UI Slider set to a predefined value

I have integrated the LeafletSlider library into my project to slide through multiple layers with different timestamps in Leaflet. My goal is to initialize the slider at the timestamp closest to the current time. In SliderControl.js, I made the following ...

Converting text to JSON using JSONP with jQuery's AJAX functionality

Potential Duplicate Question 1 Possible Duplicate Inquiry 2 I have been searching for a definitive explanation on JSONP across various questions but haven't been able to find one yet. For instance, I am attempting to make a cross domain request us ...

Testing the material-ui toggle component by simulating a click event

Trying to test functionality based on the material-ui toggle component with jest and enzyme has been challenging for me. Even though my generic clickIt function usually works well with other material-ui components, it doesn't seem to trigger the stat ...