Keep an eye out for a specific attribute within a Vue component

Is it possible to have an asynchronous operation in the parent component and then notify the child component once it has completed? Can I set up a watch in the child component to detect when a specific property changes, similar to the following example:

new Vue({
   props:['parentReady'],
   watch:{
     parentReady(val){
       alert('The parentReady prop has been changed');
     }
  }
})

Answer №1

There are multiple approaches to achieve this task. One method is to update a property in the parent component once the asynchronous operation is finished.

console.clear()

Vue.component("child", {
  props: ["parentLoading"],
  template: `
    <h1 v-if="isParentLoading">Parent is loading...</h1>
    <h1 v-else>Parent loading complete!</h1>
  `,
  computed: {
    isParentLoading() {
      return this.parentLoading
    }
  }
})

new Vue({
  el: "#app",
  data: {
    loading: true
  },
  mounted() {
    setTimeout(() => this.loading = false, 2000)
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1264677752203c203c24">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <child :parent-loading="loading"></child>
</div>

An alternative approach would be to invoke a method on the child component.

console.clear()

Vue.component("child",{
  template:`
    <h1 v-if="!loaded">Parent is loading...</h1>
    <h1 v-else>Parent loading complete!</h1>
  `,
  data(){
    return {
      loaded: false
    }
  },
  methods:{
    onLoaded(){
      this.loaded = true
    }
  }
})

new Vue({
  el:"#app",
  mounted(){
    setTimeout(() => this.$refs.child.onLoaded(), 2000)
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7305061633415d415d45">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <child ref="child"></child>
</div>

Another option could be using the watch functionality on the property.

console.clear()

Vue.component("child", {
  props: ["parentLoading"],
  template: `
    <h1 v-if="parentLoading">Parent is loading...</h1>
    <h1 v-else>Parent loading complete!</h1>
  `,
  watch: {
    parentLoading(newVal) {
      return newVal
    }
  }
})

new Vue({
  el: "#app",
  data: {
    loading: true
  },
  mounted() {
    setTimeout(() => this.loading = false, 2000)
  }
})
<script src="https://unpkg.com<@/cdn-cgi/l/email-protection#5a2c2f3f1a687468746c">[email protected]</a>

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

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Converting an ajax request from jQuery to pure JavaScript

Is there a way to convert this jQuery Ajax to plain Javascript? $("#newsLetter-form").on('submit',function(event){ event.preventDefault(); email = $('#emailId').val(); console.log(email); $.aj ...

Additional non-essential attributes (e.g. title) were provided to the component but could not be utilized

runtime-core.esm-bundler.js?d2dd:38 [Vue warn]: The component received extraneous non-props attributes (title), which could not be automatically inherited due to rendering fragment or text root nodes. at <ProductTable title="Product List" & ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

Issue with Vue directive failing to activate associated method

I have developed a unique vue directive. Vue.directive('click-outside', { bind: function (el, binding, vnode) { document.addEventListener(clickHandler, (event) => { const clickedInsideDropdown = el.contains(event.target); ...

How to Use Angular 8 to Filter an Array of Objects Based on Numeric Values

Can the list be filtered based on the value of iseidaCcaa.id? var centers = [ { id: 2, nombre: "Centro 2", iseidaCcaa: { id: 1, }, }, { id: 3, nombre: "Centro 3", iseidaCcaa: { id: 1, }, }, { id: 1 ...

Exploring Vue JS: Decoupling variables in separate files and effective ways of accessing them

In my Vue project, I am looking to create a dedicated .js file to store multiple variables that can be easily accessed by other components. I am seeking advice on the most efficient method to achieve this and would greatly appreciate any examples provide ...

Synchronization issues with form validation

I'm currently tackling an assignment for my CS50 course and I am relatively new to working with Jquery/Ajax. As part of this task, I am developing a registration form where users must enter a unique username. To achieve this, I have implemented code t ...

What could be the reason for my jQuery call displaying as undefined?

How can I extract a URL from an <a> tag and show the first paragraph of the linked page below the title? At the moment, it just shows 'undefined'. Here's my HTML: <section class="community"> <div class="news"> <ul cla ...

displaying a post-end issue on the express server

Currently, I am working on a school project that requires the development of a client-server application. The specific task is to create a webshop that can load products using AJAX. To achieve this, I am utilizing jquery and the $.load() method. Within my ...

What is the best method for eliminating a specific line from numerous HTML pages?

I have a series of HTML pages, each with a line at the top that reads: <?xml version="1.0" encoding="UTF-8" ?> When I was working on localhost, the pages opened without any issue. However, now that I have uploaded the files to the server, I am enco ...

Error message: "Unassigned value in knockout.js"

Here is my code snippet for binding to a textbox: var CategoryViewModel = { categoryModel: ko.observable({ categoryId: ko.observable(), categoryName: ko.observable(), active: ko.observable() }), GetCategoryById: functio ...

Using Vue: invoking a function with v-if

I'm currently collaborating on a Vue project that was initiated by someone else, and I do not possess much experience with Vue myself. Here is the code snippet: <div :class="{ 'results': isResults }"> <ais-stats v-slo ...

Encountering issues with webpack module federation and single-spa-vue integration, specifically with Vue version 2.16.12

I'm currently facing an issue while developing a microfrontend using single-spa-vue and Vue 2.6.12. To set up my project, I am utilizing the webpack module federation plugin. Below is the entry point for my application: src/app.ts import singleSpaV ...

What is the best way to utilize a template within a select dropdown?

Utilizing Knockout.js, I've successfully created a pseudo-select list with the following code: <div style="width:325px;height:500px;overflow:auto;" data-bind="template: { name: 'group-tmpl', foreach: explorer().categoryData }"></di ...

Subscribe on Footer triggers automatic scrolling to the bottom of the page

Whenever I fill out the form in the footer and hit submit, it directs me to a different page while automatically scrolling back down to the footer. I'm looking for a solution that prevents this automatic scrolling. I've attempted using window.sc ...

Displaying a distinct image for each Marker when hovering over them on a Map

I have implemented ReactMapGL as my Map component and I am using its HTMLOverlay feature to display a full-screen popup when hovering over markers. However, even though I have set different image data for each marker, all of them show the same image when h ...

Error message displayed when attempting to send emails through an HTML form obtained from a complimentary template site

Currently, I am in the process of learning to code basic websites but I'm facing some challenges with getting the contact form to function properly. I decided to work with a free template that can be found at this link: and uploaded it to a shared ho ...

Utilizing jQuery to Trigger a JavaScript Function in a Separate File

Here is my question: I currently have 2 files: //File1.js function TaskA() { //do something here } //File2.js function TaskB() { //do something here } $(function() { TaskA(); }); The issue I am facing is that the TaskB function in File2.js ...

How to update an HTML class using JavaScript with conditional statements

I've successfully implemented a bootstrap validation form that changes the inputField color based on error and success states. However, I'm facing an issue with changing the text-color and border-color of the Label element. I've tried vario ...