Vue momentjs update relative time in real time

前端 未结 2 992
遥遥无期
遥遥无期 2021-01-11 17:19

How I can do update relative time from momentjs in real time for user?

I have computed:

computed: {
  ago() {
     return moment().fromNow         


        
2条回答
  •  有刺的猬
    2021-01-11 18:08

    I solve this using a global "ticker" in my Vuex store. It starts incrementing itself on load every 30 seconds. Descriptive messages of the time compare to this ticker instead of to other implementations of "now" or whatever. The advantage of this technique over something like every UI element iterating its own datetime ticker every second is that you don't have reactive elements in Vue all refreshing themselves on a regular basis all willy nilly. In my application, the one global "pseudo-now" ticker iterates every 30 seconds and all elements which provide descriptive accounts of the time all refresh at once in one frame. This benefits performance.

    snippet from a relevant Vuex store:

    import Vue from 'vue'
    
    const TICKER_INTERVAL = 30000; // milliseconds
    
    let tickerPointer = null;
    
    const data = {
      state: {
        now: new Date,
      },
    
      mutations: {
        refreshTicker(state) {
          state.now = new Date;
        },
      },
    
      actions: {
        startTicker({commit}) {
          if (tickerPointer === null) {
            tickerPointer = setInterval(() => {
              commit('refreshTicker');
            }, TICKER_INTERVAL);
          }
        },
    
        haltTicker({state}) {
          clearInterval(tickerPointer);
          state.now = null;
          tickerPointer = null;
        },
    

    "StartTicker" is dispatched once by the top of my application upon load.

提交回复
热议问题