Refresh Vue component externally

I am currently working on a Laravel Vue project that features a component displaying a list of items. Upon mounting, the component triggers an AJAX call to populate the data element. However, there are other elements on the page (outside of the Vue component) that can add items to the database. I want to ensure that the list in the component remains reactive.

mounted() {
    this.getTasks();
},
methods: {
    getTasks() {
        let self = this;
        axios.get('/tasks').then(response => {
            self.tasks = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    },
}

If a user performs an action that adds a task to the list, is there a way to call the getTasks method within the component from outside the component?

Answer №1

If you want to make a function available globally in your Vue component, you can do so by declaring it when the component is mounted:

mounted() {
  windows.getTasks = this.getTasks.bind(this);
  this.getTasks();
},

Afterwards, you can use the function outside of the component by calling getTasks() or windows.getTasks()

Answer №2

If you want to manage state in your Vue.js application, consider utilizing vuex actions.

Take a look at this demonstration:

Vue.component('ChildB',{
  template:`
    <div class="child childB">
      <h1> Current Score: {{ score }} </h1>
      <button @click="changeScore">Increase Score</button>
    </div>`,
  computed: {
    score () {
      return this.$store.getters.score
    }
  },
  methods: {
    changeScore () {
      this.$store.dispatch('incrementScore', 3000)
    }
  }
})

For the complete source code and live demo, check out:

https://codepen.io/tutsplus/pen/MXpPLz

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

Transforming a jQuery Ajax request into an AngularJS $http request

I have a jQuery Ajax request that I need to convert into an AngularJS $http request. Can anyone provide guidance on how to accomplish this? $.ajax({ type: "POST", dataType: "jsonp", crossDomain: false, data:{ ...

Phase 2 "Loading" visual backdrop

I'm attempting to include a loading animation GIF in my Cycle 2 plugin. Is there a way to ensure that the GIF loads before the images? Right now, I have set my loading.gif as a background image. The issue is that the loading.gif isn't displaying ...

Troublesome Outcome: Next.js Forms Function Smoothly in Local Environment but Encounter Issues when Deploy

I am facing a puzzling issue with my Next.js application. Despite successfully using Nodemailer locally to submit forms, I keep encountering an "Internal Server Error" when deploying to cPanel. I have tried different solutions, but the problem persists. As ...

Utilize ZLIB and Node.js to create a compressed zip archive of a folder's contents

I need to compress all the files in a directory into a single ZIP file. Currently, I am using this code snippet: var fs = require('fs'); var tar = require('tar'); var zlib = require('zlib'); var path = require('path&apo ...

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

A step-by-step guide on making a list item clickable and redirecting to a URL using Vue.js

Utilizing vue.js, I have successfully configured a navigation bar with multiple list elements. However, I am seeking guidance on how to redirect one of the list elements to an external website, such as https://www.google.com/. Within my router file, each e ...

Troubleshooting: Why is Vue's v-if directive not updating after using on

I'm facing an issue where I want a div to only appear once a specific variable changes from false to true. I have tried changing the value of the variable once the component is mounted, but the v-if directive does not seem to work as expected in displ ...

What steps should I take to update all the data within a Vue object?

Essentially, I am looking to completely replace all the data in a Vue object, like so: vueobj.$data = newdata; However, the official documentation advises against this: VM156 vue.js:597 [Vue warn]: Avoid replacing instance root $data. Use nested ...

Generating one-time passwords in Node.js using Speakeasy with a specified expiration period

I'm currently utilizing https://www.npmjs.com/package/speakeasy for generating OTPs, and I want the expiration time to be set at 10 minutes. Below is the code I'm using for OTP generation: const generateOtp = function generateOtp() { let to ...

What steps do I need to take to incorporate dialog-polyfill into my React application?

Incorporating Firebase and FirebaseUI in my React application for phone number registration has been successful on Google Chrome desktop. However, when testing it on different browsers, such as through , I encountered an issue with the country code selecto ...

The functionality of Jade views is disrupted by external CSS files

I am new to node.js and apologize if this question seems too obvious. I have built my app logic with all the routes and views, and it was working fine until I tried to add more styles to my views using Jade in Express. The only change I made was including ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

How to identify duplicate values in a JavaScript array

Is there a way to check for duplicate values in an array and display an alert if any duplicates are found? Here is the function that attempts to do this: function checkDuplicateTenure(){ var f = document.frmPL0002; var supplgrid = document.getElem ...

Creating Location-Specific Customer Data using AngularJS similar to Google Analytics

Looking to create a user registration map similar to Google Analytics without actually using Google Analytics. Can anyone provide assistance with this task? I am utilizing MVC, C#, Sql Server-2014, AngularJS, and jQuery for this project. Despite my efforts ...

Discord.js encountered an error: Invalid Form Body embed.fields[0].value: Please make sure to fill in this required field

My attempts to create an order command for my discord.js bot have been unsuccessful. Whenever someone uses the command, it doesn't respond and instead presents the following error in the console: "This error originated either by throwing inside of an ...

Conquer the issue of incessant AJAX page refreshing

Currently, I am working on an application where I handle numerous form submissions and utilize ajax to send data to a server running on Node.js. One of the features includes updating a table upon button click, which triggers a spinner to load as an indic ...

Learn the process of fetching checkbox values using JavaScript with this snippet

Is it possible to retrieve the name of the selected checkbox values/labels from the following code: <input id ="abc" value="abeexch" type ="checkbox"> <input id ="nam" value="suns" type ="checkbox"> If a checkbox is selected, how can I obtain ...

Experimenting with a sample post on a minimalist Node.js application using Mocha and Superagent

I trust you are having a splendid day. Currently, I am focusing on enhancing my TDD skills in Node.js. To practice, I have developed a minimalistic application that handles basic GET and POST requests. The app simply displays a straightforward form to the ...

express-validator: display a single validation error message for each field

As a newcomer to expressjs and express-validator, I am navigating through setting up a registration form where users need to submit their email address among other details. My current validation rule for the email field using 'express-validator' ...