首页 > 解决方案 > 继续在历史记录中前后添加行

问题描述

有两个页面:Home.vueStatistics.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>

标签: javascripthtmlvue.jsvue-component

解决方案


我做了一些更改来修复您的代码

首先,您试图传递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


推荐阅读