问题
There is two pages: Home.vue and Statistics.vue. At home page, there is the interval that counts some numbers at page load. When you switch to "/statistic" page interval is stopped and when you get back to "/" page, interval and counting are start from when they stopped. Problem is, that I need to resume adding rows to "/statistic" page once when you switch from "/statistics" to "/" and back again to "/statistics". Now "/statistics" always reset values to default and start adding rows from beginning. Working code example to check solution: https://codesandbox.io/s/black-sound-rseqb
"/statistics" page:
<template>
<div class="statistics">
<table v-for="(field, index) in fields" :key="index">
<tr>
<th>Field</th>
<th>Value</th>
<th>Time</th>
</tr>
<tr v-for="(change, index) in changesArray[index]" :key="index">
<td>{{ change.field }}</td>
<td>{{ change.value }}</td>
<td>{{ change.time }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: 'Statistics',
props: {
changesA: {
type: Array,
required: true
},
changesB: {
type: Array,
required: true
}
},
data () {
return {
fields: ['A', 'B'],
changesArray: [this.changesA, this.changesB]
}
}
}
</script>
<style lang="scss" scoped>
.statistics {
display: flex;
}
table:first-of-type {
margin-right: 20px;
}
</style>
"App.vue"
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/statistics">Statistics</router-link>
</div>
<router-view :changesA.sync="changesA" :changesB.sync="changesB" />
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
changesA: [],
changesB: []
}
}
}
</script>
<style lang="scss">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
}
#nav {
padding: 30px 0;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>
回答1:
There were a couple of changes done by me to fix your code
Firstly, you were trying to pass localChanges to parent which is getting initialized on each component load which is resetting your array. It is fixed by using
this.changesA.push({ ...obj });
this.changesB.push({ ...obj });
this.$emit("update:changesA", [...this.changesA]);
this.$emit("update:changesB", [...this.changesB]);
Secondly, in your firstObjects() method, you were pushing an item at index on obj as
this.changesB.push({ ...obj[i] }); //see i
which is wrong
Also, I think you want to call firstObjects() only if the array is empty which can be done by simply putting an enclosing condition.
Fixed sandbox: https://codesandbox.io/s/live-stats-with-pause-on-route-change-lqmqo
回答2:
There is the keep-alive; as shown in Vue documentation.
<keep-alive>
<component v-bind:is="statistics"></component>
</keep-alive>
Vue Documentation: https://vuejs.org/v2/guide/components-dynamic-async.html
来源:https://stackoverflow.com/questions/61278814/resume-adding-rows-on-history-back-and-forward