What is the best approach to re-render a v-for loop in my Vue.js application when switching to another route?
In my scenario, I am using Vuex
, vuex-persistedstate
, and moment
for saving data in localStorage and displaying timestamps like "a moment ago".
However, how can I trigger a re-render of the v-for loop without changing the data from my API or manually reloading the page?
If you look at the screenshot below:
https://i.sstatic.net/kAmuV.png
The Recent Activity data is always cached in localStorage. But if there are no new updates from the API, how can I ensure that the timestamps continue to update (e.g., "3 minutes ago", "4 minutes ago") without having to refresh the page manually?
This currently only happens upon page reload because of my code structure:
<template>
<div class="widget">
<h4 class="widget-title">Recent Activity</h4>
<ul class="activitiez">
<li v-for="act in recentActivity" :key="act._id" :id="act._id">
<div class="activity-meta">
<i v-html="convertToMoment(act.created_at)"></i>
<span v-html="act.activity"></span>
<h6>by <a href="#" v-html="act.sent_name"></a></h6>
</div>
</li>
</ul>
</div>
</template>
<script>
import {mapGetters, mapActions} from "vuex"
export default {
created() {
this.fetchRecentActivityData()
},
computed: {
...mapGetters(["recentActivity"])
},
methods: {
...mapActions(["fetchRecentActivityData"]),
convertToMoment(data) {
return moment(data).fromNow()
}
},
}
</script>
<style>
</style>
And here is my Vuex store code:
import axios from 'axios';
const state = {
recentActivityStore: [],
errorBag: null,
timingStore: Date.now()
};
const getters = {
recentActivity: state => state.recentActivityStore,
recentActivityTiming: state => state.timingStore
};
const actions = {
async fetchRecentActivityData({ commit }) {
const recentAct = this.state.recentactivity.recentActivityStore
if(_.isEmpty(recentAct)) {
const response = await axios.get('/recent/activity')
commit('UPDATE_RECENT_ACTIVITY', response.data)
}
commit('UPDATE_TIMING', Date.now())
}
};
const mutations = {
UPDATE_RECENT_ACTIVITY: (state, data) => {
state.recentActivityStore = data
},
UPDATE_TIMING: (state, data) => {
state.timingStore = data
}
};
export default {
state,
getters,
actions,
mutations
};
How can I achieve auto-refreshing of my v-for loop without manual page refresh so that the timestamps keep updating? Any help would be greatly appreciated.
Thank you!