如何在 Nuxt 中使用 Prisma ORM
本指南介绍如何设置 Nuxt 应用、使用 Prisma Nuxt 模块 配置 Prisma Postgres 以及如何将项目部署到 Vercel 进行生产。
¥This guide explains how to set up a Nuxt application, configure Prisma Postgres using the Prisma Nuxt module, and deploy the project to Vercel for production.
你将学到以下内容:
¥Here's what you'll learn:
-
如何使用 Prisma Nuxt 模块设置 Nuxt 项目。
¥How to set up a Nuxt project with the Prisma Nuxt module.
-
如何在 Nuxt 应用中配置和使用带有 Prisma Nuxt 模块的 Prisma Postgres。
¥How to configure and use Prisma Postgres with the Prisma Nuxt module in your Nuxt app.
-
如何将项目部署到 Vercel。
¥How to deploy the project to Vercel.
先决条件
¥Prerequisites
要遵循本指南,请确保你已具备以下条件:
¥To follow this guide, ensure you have the following:
-
Node.js 版本:Prisma 6 需要 兼容的 Node.js 版本。
¥Node.js version: A compatible Node.js version required for Prisma 6.
-
账户:
¥Accounts:
-
基本了解 Git 和 Vercel 部署(有帮助,但非必需)。
¥Basic knowledge of Git and Vercel deployment (helpful but not required).
1. 创建新的 Nuxt 项目并设置 Prisma Nuxt 模块
¥ Create a New Nuxt Project and set up the Prisma Nuxt module
-
初始化 新的 Nuxt 项目,选择
npm
作为包管理器,并初始化 git:¥Initialize a new Nuxt project, select
npm
as the package manager and initialize git:npm create nuxt hello-world
notenpm
as it is the most stable option with the@prisma/nuxt
module. :::我们建议使用 -
进入项目目录并安装
@prisma/nuxt
模块:¥Navigate into the project directory and install the
@prisma/nuxt
module:cd hello-world
npm i @prisma/nuxt -
安装使用 Prisma Postgres 所需的 Prisma Accelerate 客户端扩展:
¥Install the Prisma Accelerate client extension as it's required to use Prisma Postgres:
npm i @prisma/extension-accelerate
-
将
@prisma/nuxt
模块及其以下配置添加到你的nuxt.config.ts
文件:¥Add the
@prisma/nuxt
module with the following configuration to yournuxt.config.ts
file:// https://nuxt.nodejs.cn/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
compatibilityDate: "2024-11-01",
modules: ["@prisma/nuxt"],
experimental: {
componentIslands: true,
},
devtools: { enabled: true },
});
2. 通过在本地运行开发服务器来设置 Prisma ORM
¥ Setup Prisma ORM by running the development server locally
使用 Prisma 模块配置 Nuxt 项目后,下一步是设置 Prisma ORM。此过程首先启动开发服务器,该服务器会自动使用 SQLite 数据库 配置 Prisma。
¥After configuring your Nuxt project with the Prisma module, the next step is to set up Prisma ORM. This process begins by starting the development server, which automatically configures Prisma with a SQLite database.
运行以下命令,启动开发服务器:
¥Run the following command to start the development server:
npm run dev
运行此命令后,系统将提示你使用 Prisma 迁移 运行数据库迁移:
¥After running this command, you will be prompted to run a database migration with Prisma Migrate:
? Do you want to migrate database changes to your database? › (Y/n)
按下键盘上的 Y 键,确认你要迁移数据库并创建初始表。
¥Confirm that you want to migrate your database and create your initial tables by hitting Y on your keyboard.
设置流程完成后:
¥Once the setup flow has terminated, it:
-
已安装 Prisma CLI。
¥Installed the Prisma CLI.
-
使用 SQLite 数据库初始化 Prisma 项目。
¥Initialized a Prisma project with a SQLite database.
-
在
schema.prisma
文件中创建示例User
和Post
模型:¥Created sample
User
andPost
models in theschema.prisma
file:prisma/schema.prisma// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
} -
从
User
和Post
模型创建数据库表上述步骤。如果没有migrations
文件夹,数据库会在你第一次启动模块时自动迁移。之后,你需要在 CLI 中手动运行npx prisma migrate dev
以应用任何架构更改。手动运行npx prisma migrate dev
命令可以更轻松、更安全地管理迁移,还可以 troubleshoot 任何与迁移相关的错误。:::¥Created the database tables for the
User
andPost
models from the previous steps.noteThe database migrates automatically the first time you start the module if there isn't a
migrations
folder. After that, you need to runnpx prisma migrate dev
manually in the CLI to apply any schema changes. Running thenpx prisma migrate dev
command manually makes it easier and safer to manage migrations and also to troubleshoot any migration-related errors. -
安装并生成 Prisma 客户端,以便你查询数据库。
¥Installed and generated Prisma Client which enables you to query your DB.
-
已安装 Prisma 工作室。
¥Installed Prisma Studio.
Prisma 设置完成后,开发服务器应在 https://localhost:3000
上启动。
¥When the Prisma setup is complete, the development server should start on https://localhost:3000
.
接下来,停止服务器,因为我们需要进行一些代码更改。
¥Next, stop the server, as we need to make some code changes.
4. 更新应用代码
¥ Update the application code
Prisma 配置完成后,下一步是更新应用代码,以便从数据库中获取并显示数据。
¥With Prisma configured, the next step is to update your application code to fetch and display data from your database.
-
在项目的根目录中,创建一个名为
components
的文件夹。¥In the root directory of your project, create a folder named
components
. -
在
components
文件夹中,创建一个名为User.server.vue
的文件。此服务器组件将从数据库中获取并显示第一个用户的名称:¥Inside the
components
folder, create a file namedUser.server.vue
. This server component will fetch and display the name of the first user from the database:components/User.server.vue<script setup>
import { withAccelerate } from "@prisma/extension-accelerate";
const prisma = usePrismaClient().$extends(withAccelerate());
const user = await prisma.user.findFirst();
</script>
<template>
<p>{{ user?.name ?? "No user has been added yet." }}</p>
</template>noteusePrismaClient()
composable with thewithAccelerate()
extension method to ensure compatibility with Prisma Postgres. This extension will also allow you to cache your queries. :::我们正在延长 -
修改根目录中的
app.vue
文件,使其包含使用 Nuxt Islands 的新服务器组件:¥Modify the
app.vue
file in the root directory to include the new server component using Nuxt Islands:app.vue<template>
<div>
<NuxtIsland name="User"></NuxtIsland>
</div>
</template> -
运行以下命令,再次启动开发服务器:
¥Run the following command to start the development server again:
npm run dev
-
通过在浏览器中打开
https://localhost:3000
上的应用来验证应用代码是否正常工作。由于数据库中尚无用户,应用将显示:¥Verify the application code is working by opening your application in a browser at
https://localhost:3000
.\ As there are no users in the database yet, the application will display:No user has been added yet.
当用户添加到数据库时,此消息将动态更新。
¥This message will dynamically update when users are added to your database.
完成这些步骤后,你的应用现在可以从 Prisma 数据库获取数据并将其渲染在前端。
¥By completing these steps, your application is now capable of fetching data from your Prisma database and rendering it on the frontend.
5. 创建 Prisma Postgres 实例
¥ Create a Prisma Postgres instance
要存储应用的数据,你将使用 Prisma 数据平台创建一个 Prisma Postgres 数据库实例。
¥To store your app's data, you'll create a Prisma Postgres database instance using the Prisma Data Platform.
按照以下步骤创建你的 Prisma Postgres 数据库:
¥Follow these steps to create your Prisma Postgres database:
-
登录 并打开控制台。
¥Log in to and open the Console.
-
在你选择的 workspace 中,单击新建项目按钮。
¥In a workspace of your choice, click the New project button.
-
在名称字段中为你的项目输入一个名称,例如 hello-ppg。
¥Type a name for your project in the Name field, e.g. hello-ppg.
-
在 Prisma Postgres 部分中,单击“开始”按钮。
¥In the Prisma Postgres section, click the Get started button.
-
在“区域”下拉菜单中,选择最接近你当前位置的区域,例如美国东部(弗吉尼亚北部)。
¥In the Region dropdown, select the region that's closest to your current location, e.g. US East (N. Virginia).
-
单击创建项目按钮。
¥Click the Create project button.
此时,你将被重定向到数据库页面,你需要等待几秒钟,同时数据库的状态将从 PROVISIONING
更改为 CONNECTED
。
¥At this point, you'll be redirected to the Database page where you will need to wait for a few seconds while the status of your database changes from PROVISIONING
to CONNECTED
.
出现绿色 CONNECTED
标签后,你的数据库即可使用!
¥Once the green CONNECTED
label appears, your database is ready to use!
然后,在“设置数据库访问”部分找到你的数据库凭据,复制 DATABASE_URL
环境变量。
¥Then, find your database credentials in the Set up database access section, copy the DATABASE_URL
environment variable`.
DATABASE_URL=<your-database-url>
后续步骤中将需要 DATABASE_URL
环境变量。
¥The DATABASE_URL
environment variable will be required in the next steps.
6. 在 Nuxt 应用中设置 Prisma Postgres
¥ Set up Prisma Postgres in your Nuxt app
Prisma Postgres 实例已准备就绪,请更新你的 Nuxt 应用以使用此数据库:
¥Now that the Prisma Postgres instance is ready, update your Nuxt application to use this database:
-
通过将现有的
DATABASE_URL
值替换为你之前复制的值来更新.env
文件。它看起来类似于:¥Update the
.env
file by replacing the existingDATABASE_URL
value with the one you previously copied. It will look similar to this:.envDATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=PRISMA_POSTGRES_API_KEY"
-
通过更改位于
prisma
文件夹中schema.prisma
文件的datasource
块中的数据库提供程序来修改schema.prisma
文件:¥Modify the
schema.prisma
file by changing the database provider in thedatasource
block of theschema.prisma
file located in theprisma
folder:prisma/schema.prismadatasource db {
provider = "postgresql"
url = env("DATABASE_URL")
} -
删除 SQLite 数据库文件(
dev.db
和dev.db-journal
)以及migrations
文件夹,它们均位于prisma
目录中。这将清理现有的 SQLite 设置,并为你的项目迁移到 PostgreSQL 做好准备。¥Delete the SQLite database files (
dev.db
anddev.db-journal
) along with themigrations
folder, all located in theprisma
directory. This cleans up the existing SQLite setup and prepares your project to migrate to PostgreSQL. -
通过运行
prisma migrate
命令为 Postgres 数据库手动创建新的迁移:¥Manually create a new migration for the Postgres database by running the
prisma migrate
command:npx prisma migrate dev --name init
-
重新启动开发服务器:
¥Start the development server again:
npm run dev
-
打开 Nuxt DevTools(依次点击 Shift+Option+D),然后点击左侧导航栏中的 Prisma 徽标以打开 Prisma Studio。然后,通过指定
name
和email
字段的值来添加新的User
记录。¥Open the Nuxt DevTools (by hitting Shift+Option+ D) and click the Prisma logo in the left sidenav to open Prisma Studio. Then add a new
User
record by specifying values for thename
andemail
fields. -
通过在
https://localhost:3000
上刷新应用来验证应用中的数据。该页面应显示你在 Prisma Studio 中添加的用户的名称。例如,如果你添加了一个名为Jon
的用户,应用将在浏览器中显示Jon
。¥Verify the data in the application by refreshing your application at
https://localhost:3000
. The page should display the name of the user you added in Prisma Studio. For example, if you added a user namedJon
, the application will displayJon
in the browser.
恭喜,你的 Nuxt 应用现已与 Prisma Postgres 完全集成!
¥Congratulations, your Nuxt app is now fully integrated with Prisma Postgres!
7. 部署到 Vercel
¥ Deploy to Vercel
按照以下步骤将集成了 Prisma Postgres 的 Nuxt 应用部署到 Vercel:
¥Deploy your Nuxt application with Prisma Postgres integration to Vercel by following these steps:
-
确保你的项目已进行版本控制并已推送到 GitHub 存储库。如果你还没有存储库,请使用 在 GitHub 上创建一个。存储库准备就绪后,运行以下命令:
¥Ensure your project is version-controlled and pushed to a GitHub repository. If you don't have a repository yet, create one on GitHub. Once the repository is ready, run the following commands:
git add .
git commit -m "Initial commit with Prisma Postgres integration"
git branch -M main
git remote add origin https://github.com/<your-username>/<repository-name>.git
git push -u origin mainnote<your-username>
and<repository-name>
with your GitHub username and the name of your repository. :::替换 -
创建新项目。请遵循 Vercel 的 导入现有项目 指南,但在 步骤 3 处停止,你将在此处配置环境变量,然后单击“部署”。
¥Create a new project. Follow Vercel's Import an existing project guide, but stop at step 3 where you will configure environment variables before clicking Deploy.
-
配置
DATABASE_URL
环境变量:¥Configure the
DATABASE_URL
environment variable:-
展开“环境变量”部分。
¥Expand the Environment variables section.
-
添加
DATABASE_URL
环境变量:¥Add the
DATABASE_URL
environment variable:-
关键:
DATABASE_URL
¥Key:
DATABASE_URL
-
值:粘贴你的 Prisma Postgres 连接 URL,例如,从 Nuxt 项目中的
.env
文件复制。请勿在未设置DATABASE_URL
变量的情况下进行部署。如果应用无法连接到数据库,你的部署将失败。:::¥Value: Paste your Prisma Postgres connection URL, e.g. by copying it from the
.env
file in your Nuxt project.warningDo not deploy without setting the
DATABASE_URL
variable. Your deployment will fail if the application cannot connect to the database.
-
-
-
点击“部署”按钮。Vercel 将构建你的项目并将其部署到实时 URL。
¥Click the Deploy button. Vercel will build your project and deploy it to a live URL.
-
打开 Vercel 提供的实时 URL,验证你的应用是否正常运行:
¥Open the live URL provided by Vercel and verify that your application is working:
-
如果你在 Prisma Studio 中添加了用户,则其名称应显示在实时网站上。
¥If you've added a user in Prisma Studio, their name should appear on the live site.
-
如果没有用户,应用将显示:
¥If no users exist, the application will display:
No user has been added yet.
-
-
要添加或管理数据:
¥To add or manage data:
-
通过 Prisma 数据平台 或本地实例打开 Prisma Studio。
¥Open Prisma Studio via the Prisma Data Platform or local instance.
-
在数据库中添加或更新用户数据。
¥Add or update user data in the database.
-
刷新你的实时站点以确认更改。
¥Refresh your live site to confirm the changes.
-
恭喜!你的 Nuxt 应用与 Prisma Postgres 集成现已上线,并在 Vercel 上完全运行。
¥Congratulations! Your Nuxt application with Prisma Postgres integration is now live and fully operational on Vercel.
注意事项
¥Considerations
本指南将帮助你通过 Nuxt 模块开始使用 Prisma Postgres。由于 Nuxt 模块正在积极发展,它并未涵盖 Prisma 的所有功能或支持所有特殊情况。如需更高级的功能或边缘部署,请考虑直接使用 Prisma。
¥This guide helps you get started with Prisma Postgres using the Nuxt module. Because the Nuxt module is actively evolving, it does not cover all of Prisma's features or support every edge case. For more advanced functionality or edge deployments, consider using Prisma directly.
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.