nuxt-papa-parse
v1.0.8
Published
Wrapper for Papa parse to use in Nuxt
Downloads
348
Maintainers
Readme
Nuxt module for Papa Parse
Nuxt module to use Papa parse as a composable.
Features
This module provides an easy way to use Papa parser on your Nuxt app and transform CSV documents to JSON and back
Quick Setup
- Add
nuxt-papa-parse
dependency to your project
# Using pnpm
pnpm add nuxt-papa-parse
# Using yarn
yarn add nuxt-papa-parse
# Using npm
npm install nuxt-papa-parse
- Add
nuxt-papa-parse
to themodules
section ofnuxt.config.ts
export default defineNuxtConfig({
modules: ["nuxt-papa-parse"],
papaparse: {
globals: true, //default is false
},
});
That's it! You can now use My Module in your Nuxt app ✨
Example
Global use
<template>
<main>
<h1>Use a csv file to test papa parser</h1>
<input type="file" aria-label="Upload CSV" @change="handleFileChange" />
<div v-if="csvData">
<pre>{{ csvData }}</pre>
</div>
</main>
</template>
<script setup lang="ts">
const csvData = ref<string | null>(null);
const handleFileChange = (event: Event) => {
const file: File | null =
(event.target as HTMLInputElement).files?.[0] || null;
if (file) {
readCsv(file);
}
};
const readCsv = (file: File) => {
const reader = new FileReader();
reader.onload = (event: ProgressEvent<FileReader>) => {
if (!event.target) {
return;
}
const csv = event.target.result;
transformCsvToJson(csv as string);
};
reader.readAsText(file);
};
const transformCsvToJson = (csv: string) => {
$papa.parse(csv, {
headers: true,
complete: (result) => {
csvData.value = JSON.stringify(result.data, null, 2);
console.log(result);
},
});
};
</script>
Composable use
<script setup lang="ts">
const papa = usePapaParse();
const csvData = ref<string | null>(null);
const handleFileChange = (event: Event) => {
const file: File | null =
(event.target as HTMLInputElement).files?.[0] || null;
if (file) {
readCsv(file);
}
};
const readCsv = (file: File) => {
const reader = new FileReader();
reader.onload = (event: ProgressEvent<FileReader>) => {
if (!event.target) {
return;
}
const csv = event.target.result;
transformCsvToJson(csv as string);
};
reader.readAsText(file);
};
const transformCsvToJson = (csv: string) => {
papa.parse(csv, {
headers: true,
complete: (result) => {
csvData.value = JSON.stringify(result.data, null, 2);
console.log(result);
},
});
};
</script>
<template>
<main>
<input type="file" aria-label="Upload CSV" @change="handleFileChange" />
</main>
</template>
Learn more in the Papa Parse documentation.