[英]Resume adding rows on history back and forward
有两个页面: Home.vue
和Statistics.vue
。 在主页上,有一个在页面加载时计算一些数字的间隔。 当您切换到“/statistic”页面时,间隔停止,当您返回“/”页面时,间隔和计数从它们停止时开始。 问题是,当您从“/statistics”切换到“/”并再次返回到“/statistics”时,我需要恢复向“/statistic”页面添加行。 现在“/statistics”总是将值重置为默认值并从头开始添加行。 检查解决方案的工作代码示例: https://codesandbox.io/s/black-sound-rseqb
“/统计”页面:
<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>
“应用程序.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>
我做了一些更改来修复您的代码
首先,您试图将localChanges
传递给父级,该父级在每个组件加载时都会初始化,这会重置您的数组。 它是通过使用固定的
this.changesA.push({ ...obj });
this.changesB.push({ ...obj });
this.$emit("update:changesA", [...this.changesA]);
this.$emit("update:changesB", [...this.changesB]);
其次,在您的firstObjects()
方法中,您将obj
上索引处的项目推送为
this.changesB.push({ ...obj[i] }); //see i
这是错误的
另外,我认为只有在数组为空时才想调用firstObjects()
,这可以通过简单地放置一个封闭条件来完成。
固定沙箱: https://codesandbox.io/s/live-stats-with-pause-on-route-change-lqmqo
有保活; 如 Vue 文档中所示。
<keep-alive>
<component v-bind:is="statistics"></component>
</keep-alive>
Vue 文档: https://v2.vuejs.org/v2/guide/components-dynamic-async.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.