CSV
如何定义、编写和查询 CSV 数据。
Nuxt Content 开箱即用地支持 CSV 文件。你可以存储和查询 CSV 格式的数据,并提供 JSON 转换和自定义分隔符的选项。
定义集合
content.config.ts
import { defineCollection, defineContentConfig, z } from '@nuxt/content'
export default defineContentConfig({
collections: {
authors: defineCollection({
type: 'data',
source: 'authors/**.csv',
schema: z.object({
name: z.string(),
email: z.string(),
avatar: z.string()
})
})
}
})
创建 .csv 文件
在 content/authors/ 目录下创建作者文件。
id,name,email
1,John Doe,john@example.com
2,Jane Smith,jane@example.com
3,Alice Johnson,alice@example.com
name,role,avatar
John Doe,Developer,https://avatars.githubusercontent.com/u/1?v=4
Jane Smith,Designer,https://avatars.githubusercontent.com/u/2?v=4
每个 CSV 文件都应包含一个标题行,用于定义列名称,这些列名称在解析时将用作对象键。
配置
你可以在 nuxt.config.ts 中配置如何解析 CSV 文件:
nuxt.config.ts
export default defineNuxtConfig({
content: {
build: {
csv: {
// Convert CSV data to JSON objects
json: true,
// Specify custom delimiter (default is ',')
delimiter: ','
}
}
}
})
示例用法
在你的 content 目录中创建一个 CSV 文件:
content/users.csv
id,name,email
1,John Doe,john@example.com
2,Jane Smith,jane@example.com
在你的组件中查询数据:
<script setup>
const { data } = await useAsyncData('users', () =>
queryCollection('users').find()
)
</script>
<template>
<ul>
<li v-for="user in data" :key="user.id">
{{ user.name }} ({{ user.email }})
</li>
</ul>
</template>
在配置中设置 json: true 后,每一行将被转换为一个 JavaScript 对象,其中标题行用作键:
[
{
"id": "1",
"name": "John Doe",
"email": "john@example.com"
},
{
"id": "2",
"name": "Jane Smith",
"email": "jane@example.com"
}
]
自定义分隔符
如果你的 CSV 文件使用不同的分隔符,你可以在配置中指定它:
nuxt.config.ts
export default defineNuxtConfig({
content: {
build: {
csv: {
delimiter: ';' // Use semicolon as delimiter
}
}
}
})
这将解析如下的 CSV 文件:
id;name;email
1;John Doe;john@example.com
如果不需要 CSV 支持,可以通过在配置中设置
csv: false 来禁用 CSV 解析器。