首页 > 解决方案 > 从组件获取数据到另一个页面视图

问题描述

有一个组件“TableFields.vue”,两个视图文件“Home.vue”和“Statistics.vue”。
在组件中,我在对象下有changes: []变量。data()

  data () {
    return {
      startStopA: true,
      startStopB: true,
      initialValueA: 3,
      initialValueB: 3,
      randomNumbersArray: [],
      randomSignA: '+',
      randomSignB: '+',
      signsArray: ['+', '-'],
      intervalA: null,
      intervalB: null,
      changes: []
    }
  },

changes数组动态地从calculationsA()函数中获取对象。

    calculationsA () {
      this.randomSignA = this.signsArray[
        Math.floor(Math.random() * this.signsArray.length)
      ]
      this.randomSignA === '+'
        ? (this.initialValueA += this.randomNumbersArray[0])
        : (this.initialValueA -= this.randomNumbersArray[0])
      const d = new Date()
      // console.log(d.toLocaleTimeString())
      // console.log(this.randomNumbersArray[0])
      // this.changes.push(this.randomNumbersArray[0])
      // this.changes.push(d.toLocaleTimeString())
      // console.log(this.changes)
      const newChange = {}
      newChange.field = 'A'
      newChange.value = this.randomNumbersArray[0]
      newChange.time = d.toLocaleTimeString()
      this.changes.push(newChange)
    },

如何changes: []TableField.vue组件传递到Statistics.vue页面,以便使用changes数组对象数据对动态表进行编码。我不确定,我是否需要创建新组件,或者没有它也可以完成。基本上,这是TableField.vue出于测试目的而实现的组件的工作代码,可以从中看出Home.vue是根 url。

    <div class="statistics">
      <table>
        <tr>
          <th>Field</th>
          <th>Value</th>
          <th>Time</th>
        </tr>
        <tr v-for="item in changes" :key="item.value">
          <td>{{ item.field }}</td>
          <td>{{ item.value }}</td>
          <td>{{ item.time }}</td>
        </tr>
      </table>
    </div>
  </div>

我需要该代码才能在Statistics.vue页面上工作。为了更方便,
这里是 gitlab repo 的链接。

标签: javascripthtmlvue.jsvue-componentpass-data

解决方案


据我说,更好的解决方案应该是使用 Vuex ( https://vuex.vuejs.org/ ),它允许您将数据存储在名为 store 的共享点中。

或者,您可以使用此处记录的事件:https ://vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components


推荐阅读