Updating functions in child components in Vue.js

I am facing a challenge with my child component that has a prop and a mounted function to initialize date and time. How can I update this function when the data from the parent is reloaded?

Here is the code for the Parent component:

 <template>
      <div>
        <ul>
          <li v-for="item in occurrences">
            {{ item.title }} {{ item.completed }}</small>
          </li>
        </ul>
        <sourceupd class="source" v-bind:source='source'></sourceupd>
      </div>
    </template>

    <script>
      import axios from 'axios'
      import sourceupd from './SourceAndUpdated'

      export default {

        name: 'Occurrences',

        components: {
          sourceupd
        },

        data: function () {
          return {
            occurrences: [],
            source: 'ANPC'
          }
        },

        mounted: function () {
          var _self = this

          function callAPI () {
            // call api code
          }

          callAPI()

          setInterval(() => {
            callAPI()
          }, 1024 * 3)
        }
      }
    </script>

And here is the code for the Child Component:

<template lang="html">
    <small class="source-ref">Fonte: {{ source }} | Actualização:{{ updated.hour }}:{{ updated.minutes }}</small>
</template>

<script>
import moment from 'moment'

export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],

  mounted: function () {
    moment.locale('pt')

    this.updated.hour = moment().format('HH')
    this.updated.minutes = moment().format('mm')
    this.updated.seconds = moment().format('ss')
  }
}
</script>

I'm looking for a way to update the time when callAPI() is reloaded. As a newcomer to Vue.js (or frameworks in general), I'm finding it challenging to manage dynamic information like this.

Thank you for your help!

Answer №1

There are a few ways to tackle this issue.

If the source property in your parent component is modified by callAPI, you can easily handle it by moving your code into the updated handler.

export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],
  methods: {
    update(){
      moment.locale('pt')

      this.updated.hour = moment().format('HH')
      this.updated.minutes = moment().format('mm')
      this.updated.seconds = moment().format('ss')

    }    
  },
  updated: function () {
    this.update()
  },
  mounted: function(){
    this.update()
  }
}

If it's not clear whether you are updating any properties of sourceupd, another approach would be to invoke the method using a ref.

In the Parent component template:

<sourceupd ref="sourceupd" class="source" v-bind:source='source'></sourceupd>

In your mounted handler:

setInterval(() => {
  callAPI()
  this.$refs.sourceupd.update()
}, 1024 * 3)

Make sure to update the sourceupd component:

export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],

  methods: {
    update(){
      moment.locale('pt')

      this.updated.hour = moment().format('HH')
      this.updated.minutes = moment().format('mm')
      this.updated.seconds = moment().format('ss')

    }    
  },

  mounted: function () {
    this.update()
  }  
}

Don't forget to include seconds in the updated property of your data for reactivity.

  updated: {
    hour: '',
    minutes: '',
    seconds: ''
  }

Answer №2

In my opinion, I would pass the updated as a property to the child component. This way, any updates made to the parent will automatically reflect in the child component.

Instead of using an object, I suggest using a timestamp for easier manipulation and flexibility.

Another suggestion is to utilize filters for formatting the hours, minutes, and seconds.

If I were to create a Child component, it might look something like this:

const Child = {
  props: {
    updated: Number,
  },

  filters: {
    format (timestamp, format) {
      return moment(timestamp).format(format || 'dddd, MMMM Do YYYY, h:mm:ss a')
    },
  },

  template: `
    <div class="child">{{ updated | format('ss') }}</div>
  `,
}

By updating the parent's updated property, the changes will seamlessly flow down into the child component.

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

"Exploring the power of Vue3's composables in rendering

Can a composable function be created to utilize a render function for displaying content? For example: import { h } from 'vue' export function useErrorHandling() { return { render() { return h('div', { class: 'bar&a ...

How can I add a suffix to a dataset in Chart.js?

Utilizing Chart.js to present data on my website, I am seeking a way to include a suffix indicating that the values are in grams (g). Although the documentation does not offer much assistance on this feature, it appears to be a straightforward addition. F ...

What is the best way to completely eliminate a div from a webpage

I've created a new div element using jQuery: $(document.body).append('<div id="test"></div>'); Then, I display a success message and remove the div after 10 seconds: $('test').html('SUCCESS!'); setT ...

Error: ChunkLoadError encountered when trying to load the "blogs-component" chunk in Laravel Vuejs

Despite smooth functioning on local development, my Laravel + Vuejs project is encountering ChunkLoadError on 2 pages. After consulting similar cases on SO and confirming the file's existence in the output path, the issue persists. The affected page ...

The post processing effect in Three.js does not support FXAA when SSAO is activated

I am having trouble getting SSAO and FXAA effects to work together in this simple test scene. Enabling SSAO works fine, but when I also enable FXAA, the render turns black. In the provided fiddle, if you uncomment composer.addPass(FXAA_effect); you will s ...

What causes the successful implementation of camelCase attributes in TypeScript to result in an error when used in JavaScript with React?

I'm currently developing my own React component library in TypeScript, which I seamlessly integrate with React JS projects. While everything works smoothly when using the components in TypeScript, I encounter errors in the console when working in JS. ...

How can I monitor changes in window properties using Vue.js?

I'm having trouble monitoring an object for tracking called window.gtmDataObject. As new objects are pushed to the array window.gtmDataObject during website interactions, I am attempting to monitor each time this global variable is updated with new ob ...

Python Selenium Tutorial: Selecting an Option from a Dropdown Menu

I need to automate the process of updating the page located at using Python-Selenium. Specifically, I want to simulate clicking on 'Choose an organism -> Homo sapiens', and then clicking on 'Update'. Can someone guide me on how to ...

Utilizing TypeScript interfaces for implementing useFirestore() function - a guide

I have implemented the useFirestore() wrapper from VueUse.org in my project. However, I encountered an issue when using useFirestore() with a generic and trying to work with interfaces containing optional properties. TypeScript throws an error in such cas ...

Javascript floating navigation toolbar

How can I create a minimalist launch bar with a search button that only appears on a page when a specific hotkey is pressed? I want to avoid using large libraries like mootools or FancyBox for this Chrome Extension project to keep it lightweight. Do you ...

Adjusting the tab order dynamically within a navigation menu

I am currently facing an issue where the focus is not being ignored when the drawer is closed. Even with the showDrawer reference set to false, I can still tab through links in the closed drawer. Setting tabindex="-1" on the <nav> element does not pr ...

A space designated for numerous receivers

Is there a way to create a field that contains other elements, similar to sending messages to multiple users in a social network? https://i.stack.imgur.com/P9e24.png I attempted to understand the code for this, but it's quite complex. If anyone could ...

Display debugging information in the console using bunyan

child.log.info('info'); child.log.debug('debug'); When running the command: node app.js | bunyan -o short -l debug I am encountering an issue where only INFO messages are displayed and DEBUG messages are not showing up. I want to be ...

Guide on Integrating Vue Router with Vue Material Tabs

Exploring Vue Material Tabs functionality, I'm curious to find out if it's possible to integrate Vue Router with tabs. Essentially, I want each active tab to correspond to a different route. For example: Clicking on Tab 1 should lead to the r ...

Combine two functions into a single one to streamline and avoid overlap

Recently, I set up an exclusive checkbox feature within my HTML code. This feature includes 2 <input> elements along with two <button> elements that are also exclusive and have black/white color options based on the input they are associated wi ...

How can VueJS cycle through the arrays within an object?

Is there a way to efficiently iterate through arrays within an object like in this example? I have a simple code snippet that currently outputs indexes in order, but I'm looking to access the values of the array instead. <template> <div&g ...

Transform a list of H1..6 into a hierarchical structure

I have a task to convert H1 to H6 tags from a markdown file into a JavaScript hierarchy for use in a Table of Contents. The current list is generated by AstroJS and follows this format [{depth: 1, text: 'I am a H1'}, {depth: 2: 'I am a H2}] ...

JavaScript code to convert a query into an array

Is there a way to search through a JavaScript array to find all names that start with the letter A? If so, how can I display all of the information associated with those names? Name":"Albert","age":"14" Name":"Alison","age":"14" Here is my JSON array: ...

What are the typical methods for implementing middleware in Node.js using the Express and Connect frameworks?

Exploring the proper way to utilize middlewares in a growing Node.js web project using Express and Connect. While there are middlewares that handle requests globally, there are often specific tasks such as processing incoming data that are only relevant t ...

Use jQuery to simulate a keydown event on a text input and ensure the value is preserved after the

When utilizing Tampermonkey on a website built with angularjs, I am facing an issue. I want to prefill an input box with a specific value upon opening the URL, but the search function is activated by typing. Therefore, I require a keydown event like pressi ...