使用vue-xlsx解析Excel后如何在methods中访问返回的JSON数据
解决方案
核心原因是你现在拿到的collection是xlsx-json组件通过作用域插槽暴露的参数,只能在插槽对应的模板范围内使用,和你在data里定义的collection变量没有关联,所以在业务方法里访问不到。
你只需要在插槽内加一步赋值操作,把插槽拿到的数据同步到组件实例的data里即可,修改后的代码如下:
<template> <div> <input type="file" @change="onChange" /> <xlsx-read :file="file"> <xlsx-json> <template #default="collection"> <div> {{ collection }} <!-- 新增这行,把插槽数据同步到data里 --> {{ saveCollection(collection) }} </div> </template> </xlsx-json> </xlsx-read> <!-- 可自行加按钮触发提交逻辑 --> <button @click="sendJson">提交JSON数据</button> </div> </template> <script> import { XlsxRead, XlsxJson } from "vue-xlsx"; export default { components: { XlsxRead, XlsxJson, }, data() { return { file: null, collection: null, }; }, methods: { onChange(event) { this.file = event.target.files ? event.target.files[0] : null; // 这里打印拿不到是正常的,此时文件还没完成解析 }, // 新增数据保存方法 saveCollection(data) { // 加判断避免重复赋值导致的性能问题 if (JSON.stringify(data) === JSON.stringify(this.collection)) return this.collection = data console.log('解析完成的数据:', this.collection) }, sendJson() { if (!this.collection) { alert('请先选择Excel文件') return } // 这里就可以正常遍历使用数据了 this.collection.forEach(item => { console.log(item.name) }) }, }, };
注意事项
- 不要在
onChange方法里直接访问collection,文件选中后组件需要先完成解析才会触发插槽渲染,赋值逻辑才会执行,collection才会有值
内容的提问来源于stack exchange,提问作者Eamonn El Gendy
相关产品推荐
相关产品推荐

