【问题标题】:Vue bind emit data to tableVue绑定发射数据到表
【发布时间】:2019-01-05 04:57:48
【问题描述】:

我正在尝试编写我的第一个 Vue 应用程序,它将允许 CSV 上传并在表格中显示数据。我可以上传文件并将内容渲染到控制台,然后用 Papa 解析 CSV。不过,我似乎无法将文件中的数据绑定到表中。我开始 here 并添加了 Papa 解析以进行 CSV 处理。

下面是相关代码:

Main.js

import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false

  /* eslint-disable no-new */
  new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

上传.vue 组件

<template>
    <h1>Upload CSV</h1>
    <input type='file' @change='loadTextFromFile'>
</template>

<script>
// csv parsing
import Papa from 'papaparse'

export default {
  methods: {
    loadTextFromFile (event) {
      if (!event.target.files[0]) {
        alert('Upload a file.')
      } else {
        let file = event.target.files[0]
        if (file) {
          let reader = new FileReader()
          let config = {
            delimiter: ',',
            newline: '',
            quoteChar: '"',
            escapeChar: '"',
            header: false,
            trimHeaders: false
          }
          // reader.onload = e => this.$emit('load', e.target.result)
          reader.onload = e => this.$emit('load', Papa.parse(event.target.result, config))
          // trace what was emitted
          reader.onload = function (event) {
            let results = Papa.parse(event.target.result, config)
            console.log('PAPA RESULT: ', results.data)
            console.log('ROWS:', event.target.result)
          }
          reader.readAsText(file)
        } else {
          alert('Please select a file to upload.')
        }
      }
    }
  }
}
</script>

<style>
</style>

App.vue

<template>
  <div id="app">
    <h1>My CSV Handler</h1>
    <br>
    <upload @load="items = $event"></upload>
    <br>
    <table>
      <thead>
      </thead>
      <tbody>
        <!-- eslint-disable-next-line -->
        <tr v-for="row in items">
              <td>{{ row }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import Upload from './components/Upload'

export default {
  name: 'app',
  data: () => ({ items: [] }),
  components: {
    Upload
  }
}
</script>

<style>
</style>

如果我发出原始 e.target.result 并将 App.vue 中的任何地方的“项目”更改为“文本”,我可以像教程一样成功地将文本数据渲染到文本区域。

谢谢!

【问题讨论】:

    标签: javascript vue.js binding vuejs2 vue-component


    【解决方案1】:

    您遇到了阵列反应性的限制。查看解释caveats 的文档。

    当您通过直接设置索引(例如 arr[0] = val)或修改其长度属性来修改数组时。同样,Vue.js 也无法获取这些更改。始终使用 Array 实例方法修改数组,或完全替换它。

    Source

    这里有一个快速的fiddle,展示了如何使用splice 来替换items 数组,使其能够对更新做出反应。

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2020-01-06
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2020-05-12
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多