creating a live countdown on rows of a table using vuejs

Check out this jsfiddle link

Within vuejs, I have a table with countdown functionality for listing data. However, I'm facing an issue where I cannot initiate multiple countdowns in separate rows of the table. To illustrate this problem further, I have created a jsfiddle demonstration linked above. Your insights and assistance on this matter would be greatly appreciated. Thank you in advance.

new Vue({
  el: '#q-app',
  data: function () {
    let now = new Date();
    return {
    countdown: null,
      data: [
        {
          name: 'calories',
          calories: 159,
          fat: 6.0,
          carbs: 24,
          tarih: "2020-11-11"
        },
        {
          name: 'fat',
          calories: 237,
          fat: 9.0,
          carbs: 37,
          tarih: "2020-11-11 11:00"
        },
        {
          name: 'carbs',
          calories: 518,
          fat: 26.0,
          carbs: 65,
          tarih: "2020-11-11 11:00"
        },
        {
          name: 'protein',
          calories: 305,
          fat: 3.7,
          carbs: 67,
          tarih: "2019-07-11 11:00"
        }
      ],
      // date:moment(now).format('YYYY-MM-DD HH:mm'),
      columns: [

        { name: 'calories', align: 'center', label: 'Calories', field: 'calories', sortable: true },
        { name: 'fat', label: 'Fat (g)', field: 'fat', sortable: true },
        { name: 'carbs', label: 'Carbs (g)', field: 'carbs' },
        { name: 'tarih', label: 'Protein (g)', field: row => {
            let datem = moment(row.tarih).format('YYYY-MM-DD HH:mm')
          let selfi = this;
          setInterval(function () {

             selfi.countdown=countdown(new Date(datem).getTime());
          }, 1000);
        }
        },

      ],
    }
  },
  methods:{

  },
  mounted(){

  }
})

Answer №1

Check out this handy solution: https://jsfiddle.net/fzr36qwc/1/

In this method, a countdown field is assigned to each row and then updated periodically using setInterval.

new Vue({
  el: '#q-app',
  props:[
  'datam'
  ],
  data: function () {
    return {
      data: [
        {
          name: 'calories',
          calories: 159,
          fat: 6.0,
          carbs: 24,
          tarih: "2020-11-11",
          sodium: 87,
          calcium: '14%',
          iron: '1%',
          countdown: null,
        },
        {
          name: 'fat',
          calories: 237,
          fat: 9.0,
          carbs: 37,
          tarih: "2020-11-11 11:00",
          sodium: 129,
          calcium: '8%',
          iron: '1%',
          countdown: null,
        },
        {
          name: 'carbs',
          calories: 518,
          fat: 26.0,
          carbs: 65,
          tarih: "2020-11-11 11:00",
          sodium: 54,
          calcium: '12%',
          iron: '6%',
          countdown: null,
        },
        {
          name: 'protein',
          calories: 305,
          fat: 3.7,
          carbs: 67,
          tarih: "2020-11-11 11:00",
          sodium: 413,
          calcium: '3%',
          iron: '8%',
          countdown: null,
        }
      ],
      columns: [

        { name: 'calories', align: 'center', label: 'Calories', field: 'calories', sortable: true },
        { name: 'fat', label: 'Fat (g)', field: 'fat', sortable: true },
        { name: 'carbs', label: 'Carbs (g)', field: 'carbs' },
        { name: 'tarih', label: 'Protein (g)', field: 'countdown'},
      ],
    }
  },
  methods:{
    updateCountdowns() {
      Object.values(this.data).forEach(row => {
        let datem = moment(row.tarih).format('YYYY-MM-DD HH:mm');
        row.countdown = countdown(new Date(datem).getTime()).toString();
      })
    }
  },
  mounted(){
    // Initial Countdown Update
    this.updateCountdowns()
    // Automatic Update Every Second
    setInterval(this.updateCountdowns, 1000)
  }
})

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

What causes a user to log out when the page is refreshed in a React/Redux application?

Each time the page is reloaded in my React/Redux application, the user gets logged out, even though I have stored the token in localStorage. There seems to be an error somewhere. The token should ideally be saved when the user logs in and not lost upon rel ...

Converting nested lists into arrays: A deep dive into Eloquent JavaScript's fourth chapter

I'm stuck on this exercise and could really use some help to complete it. Can someone show me how to finish it and explain the solution? Thanks a lot! There's a list value called "values" that needs to be converted into an array format like [1, ...

Using Node.js to Send Parameters in a POST Request

I have a node.js application with an express framework and a POST route defined as follows: app.post('/test', function(req, res){ //res.send(req.body.title + req.body.body) console.log(req.params); console.log(req.body); console.log(req.bod ...

Attempting to retrieve the name of my controller and action within a JavaScript file

After checking out the Stack Overflow link here, I came across a suggested solution: var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()'; However, despite implementing this code in my JavaScript file, it does not yield ...

The angular event broadcaster controller is currently unavailable

In my app, there is a search box and a list of results. The search box is controlled by SearchCtrl, while the list of results is managed by DocListCtrl. When a user submits a query, SearchCtrl emits an event that DocListCtrl listens for in order to update ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Switch back and forth between input and textarea, but only if the content exceeds a certain length

In my current project, I am working on a feature where I need to display a textarea whenever the user clicks in the input and the length of its content exceeds 20 characters. If not, the normal input should continue to be displayed. However, I seem to be ...

Invoking a plugin method in jQuery within a callback function

Utilizing a boilerplate plugin design, my code structure resembles this: ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.pro ...

Spreading activity among react elements

Recently, I decided to repurpose a login/register modal by incorporating a Modal to manage its visibility. In the index.js file, I made the following changes: const Form = ({ initialState = STATE_SIGN_UP, showPopUp = STATE_HIDE }) => { const [mode, t ...

Is it possible to transform this nested promise into a chain instead?

This situation is just a scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise | model <= items | | :sync ...

Form validation errors were detected

Currently, I am working with a formgroup that contains input fields with validations set up in the following manner: <mat-form-field class="mat-width-98" appearance="outline"> <mat-label>Profession Oc ...

Transitioning to offline mode with cypress resulted in a promise that remained unresolved

Can anyone assist me with following the official guidelines from Cypress on how to enter offline mode? Encountered an error => The callback function returned a promise that never resolved. Here is the callback function in question: () => { ret ...

Combine Woocommerce Product Bundles with Ajax Cart additions and the ability to continue shopping after adding items to your cart

I am currently working on implementing the functionality to add WooCommerce product bundles to my cart using ajax. Once the products are successfully added, I want two buttons to be displayed - one for viewing the cart and the other for continuing shopping ...

I am trying to customize the colors of each Y-axis grid line in Chart.JS based on their corresponding values

Utilizing MVC 4.0 and chart.JS for graph generation, I have successfully implemented horizontal lines on the Y axis using the following property: scaleShowGridLines = true; scaleShowHorizontalLines: true, //Boolean - Whether to show vertical lines (except ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

Storing a chosen value in Vuex store: a simple guide

I need help with storing the selected value from a dropdown in Vuex store: <select name="lang" v-model="lang" @change="setLanguage($event.target.value)"> <option key="0" value="en&qu ...

Text inside the placeholder is not displaying correctly in the React.js user interface

When passing placeholder text as a prop to the <FormField/> component from the <CreatePost/>, I encountered an issue where the placeholder text was not displaying in the form. Interestingly, when I used console.log within the <FormField/> ...

refresh information using ckeditor

I've been facing an issue with updating the content in my CKEditor <textarea id="monday" class="ckeditor" name="monday" >1</textarea> <script type="text/javascript" > setTimeout(function(){ $('#monday').val(&ap ...

DescribeModel is displaying unusual behavior

Should the following behavior be expected? Parent Component: <template> <child v-model:counter="counter" /> </template> <script setup lang="ts"> import {ref} from 'vue'; import child from './chil ...

How can you trigger a page method from a layout event in Vue.js?

I'm working on a design that includes a sidebar and an image gallery on the page. Initially, all images are loaded without any filters applied. However, when a button in the sidebar is clicked, I want the page to display filtered images. Although I ca ...