Nuxt 3 入门
¥Getting Started with Nuxt 3
Strapi 文档团队专注于改进 Strapi 5 核心体验的文档。我们将在未来 6 个月内发布许多更改,请密切关注👀。
¥The Strapi Documentation team focuses on improving the documentation for Strapi 5's core experience. We will release many changes in the next 6 months, so please keep an eye out 👀.
因此,当前页面现在仅处于维护模式,可能未完全与 Strapi 5 保持同步,并且很快将从 docs.strapi.io 中删除并移至 Strapi 的 集成页面。
¥As a result, the present page is now in maintenance mode only, might not be fully up-to-date with Strapi 5, and will soon be removed from docs.strapi.io and moved to Strapi's integrations page.
同时,如果你想帮助我们改进此页面,请随时 contribute 到文档的 GitHub 存储库。
¥In the meantime, if you want to help us improve this page, please feel free to contribute to the documentation's GitHub repository.
本集成指南遵循 快速入门指南。你应该能够通过浏览 URL http://localhost:1337/api/restaurants 使用该 API。
¥This integration guide follows the Quick Start Guide. You should be able to consume the API by browsing the URL http://localhost:1337/api/restaurants.
如果你尚未阅读快速入门指南,则使用 Nuxt 3 请求 Strapi API 的方式将保持不变,只是你不获取相同的内容。
¥If you haven't gone through the Quick Start Guide, the way you request a Strapi API with Nuxt 3 remains the same except that you do not fetch the same content.
创建 Nuxt 3 应用
¥Create a Nuxt 3 app
使用 npx package runner 创建基本的 Nuxt 3 应用
¥Create a basic Nuxt 3 application with npx package runner
npx nuxi init nuxt-app
使用 HTTP 客户端
¥Use an HTTP client
在这个例子中,我们使用了很棒的 @nuxt/strapi 模块和 Nuxt 辅助函数 $获取(基于 ohmyfetch
)。你可以选择其中任何一个变体。
¥For this example we are using the awesome @nuxt/strapi module and Nuxt helper function $fetch (based on ohmyfetch
). You may choose any of this variants.
- @nuxtjs/strapi
- fetch
yarn add --dev @nuxtjs/strapi
将 @nuxtjs/strapi
添加到 nuxt.config.ts
的模块部分,设置如下:
¥Add @nuxtjs/strapi
to the module section of nuxt.config.ts
with the following settings:
modules: ['@nuxtjs/strapi'],
strapi: {
url: 'http://localhost:1337'
},
无需安装。
¥No installation needed.
获取请求 - 获取实体或一个实体的列表
¥GET Request - get list of entities or one entity
对 restaurant
集合类型执行 GET
请求以获取你的餐厅。
¥Execute a GET
request on the restaurant
collection type in order to fetch your restaurants.
确保你激活了 restaurant
集合类型的 find
和 findOne
权限。
¥Be sure that you activated the find
and findOne
permission for the restaurant
collection type.
- @nuxtjs/strapi
- fetch
@nuxtjs/strapi
公开了由 Nuxt 3 自动导入的可组合项。请注意,delete
函数必须重命名,因为它是 JavaScript 中的保留字。
¥@nuxtjs/strapi
exposes composables that are auto-imported by Nuxt 3. Note that delete
function must be renamed because it's reserved word in JavaScript.
<script setup lang="ts">
import type { Restaurant } from '~/types'
const { find, findOne, create, update, delete: remove } = useStrapi()
</script>
// Get all restaurants
const response = await find<Restaurant>('restaurants')
// Get one restaurant by id
const response = await findOne<Restaurant>("restaurants", restaurantId)
// Get all restaurants
const response = $fetch("http://localhost:1337/api/restaurants")
// Get one restaurant by id
const response = await $fetch(`http://localhost:1337/api/restaurants/${restaurantId}`)
// List of the restaurants
{
"data": [
{
"id": 1,
"attributes": {
"name": "Biscotte Restaurant",
"description": "Welcome to Biscotte restaurant! \nRestaurant Biscotte offers a cuisine based on fresh, quality products, often local, organic when possible, and always produced by passionate producers.",
"createdAt": "2022-10-29T09:37:55.061Z",
"updatedAt": "2022-11-07T18:53:27.702Z",
"publishedAt": "2022-10-29T09:47:48.782Z"
}
},
{
"id": 2,
"attributes": {
"name": "Dolemon Sushi",
"description": "Unmissable Japanese Sushi restaurant. The cheese and salmon makis are delicious.",
"createdAt": "2022-10-29T09:37:55.061Z",
"updatedAt": "2022-11-07T18:53:27.702Z",
"publishedAt": "2022-10-29T09:47:48.782Z"
}
}
],
"meta": {
"pagination": { "page": 1, "pageSize": 25, "pageCount": 1, "total": 4 }
}
}
// One restaurant
{
"data": {
"id": 1,
"attributes": {
"name": "Biscotte Restaurant",
"description": "Welcome to Biscotte restaurant! \nRestaurant Biscotte offers a cuisine based on fresh, quality products, often local, organic when possible, and always produced by passionate producers.",
"createdAt": "2022-10-29T09:37:55.061Z",
"updatedAt": "2022-11-07T18:53:27.702Z",
"publishedAt": "2022-10-29T09:47:48.782Z"
}
},
"meta": {}
}
邮寄请求 - 创建新实体
¥POST Request - create new entity
对 restaurant
集合类型执行 POST
请求以创建餐厅。
¥Execute a POST
request on the restaurant
collection type in order to create a restaurant.
确保你激活了 restaurant
集合类型的 create
权限。
¥Be sure that you activated the create
permission for the restaurant
collection type.
- @nuxtjs/strapi
- fetch
await create<Restaurant>("restaurants", {
name: restaurantName,
description: restaurantDescription })
await $fetch("http://localhost:1337/api/restaurants", {
method: "POST",
body: {
data: {
name: restaurantName,
description: restaurantDescription
}
}
})
放置请求 - 更新现有实体
¥PUT Request - update existing entity
对 restaurant
集合类型执行 PUT
请求以更新你的餐厅。
¥Execute a PUT
request on the restaurant
collection type in order to update your restaurant.
确保你激活了 restaurant
集合类型的 put
权限。
¥Be sure that you activated the put
permission for the restaurant
collection type.
- @nuxtjs/strapi
- fetch
await update<Restaurant>("restaurants", restaurantId, {
name: restaurantName,
description: restaurantDescription })
await $fetch(`http://localhost:1337/api/restaurants/${restaurantId}`, {
method: "PUT",
body: {
data: {
name: restaurantName,
description: restaurantDescription
}
}
})
删除请求 - 删除现有实体
¥DELETE Request - delete existing entity
对 restaurant
集合类型执行 DELETE
请求以删除你的餐厅。
¥Execute a DELETE
request on the restaurant
collection type in order to delete your restaurant.
确保你激活了 restaurant
集合类型的 delete
权限。
¥Be sure that you activated the delete
permission for the restaurant
collection type.
- @nuxtjs/strapi
- fetch
await remove<Restaurant>("restaurants", restaurantId);
await $fetch(`http://localhost:1337/api/restaurants/${restaurantId}`, {
method: 'DELETE'
})
示例
¥Example
考虑一个实现上述功能的简单 CRUD Nuxt 应用的示例。
¥Consider an example of a simple CRUD Nuxt application that implements the functions described above.
- @nuxtjs/strapi
- fetch
./pages/index.vue
<template>
<div>
<ul>
<li v-for="restaurant in restaurants?.data" :key="restaurant.id">
{{ restaurant.attributes.name }}
<button @click="$router.push(`${$route.path}/restaurant/${restaurant.id}`)">Edit</button>
<button @click="deleteRestaurant(restaurant.id)">Delete</button>
</li>
</ul>
<nuxt-link :to="`${$route.path}/restaurant/create`">Create</nuxt-link>
</div>
</template>
<script setup lang="ts">
import type { Restaurant } from '~/types'
const { find, delete: remove } = useStrapi() // delete is keyword in JS, must not be used
const { data: restaurants, refresh } = await useAsyncData(
'restaurants',
() => find<Restaurant>('restaurants')
)
const deleteRestaurant = async (restaurantId: number) => {
await remove<Restaurant>("restaurants", restaurantId);
refresh()
};
</script>
./pages/restaurant/create.vue
<template>
<div>
<div><input type="text" v-model="name" /></div>
<div><textarea v-model="description"></textarea></div>
<button @click="createRestaurant();$router.go(-1)">Create</button>
<button @click="$router.go(-1)">Cancel</button>
</div>
</template>
<script setup lang="ts">
import type { Restaurant } from "~/types"
const { create } = useStrapi()
const name = ref("")
const description = ref("")
const createRestaurant = async () => {
await create<Restaurant>("restaurants", {
name: name.value,
description: description.value
})
</script>
./pages/restaurant/[id].vue
<template>
<div>
<div><input type="text" v-model="name" /></div>
<div><textarea v-model="description"></textarea></div>
<button @click="updateRestaurant();$router.go(-1)">Update</button>
<button @click="$router.go(-1)">Cancel</button>
{{ restaurant }}
</div>
</template>
<script setup lang="ts">
import type { Restaurant } from '~/types'
const { findOne, update } = useStrapi()
const route = useRoute()
const restaurantId: number = +route.params.id // cast to number
const response = await findOne<Restaurant>("restaurants", restaurantId)
const name = ref(response.data.attributes.name)
const description = ref(response.data.attributes.description)
const updateRestaurant = async () => {
await update<Restaurant>("restaurants", restaurantId, {
name: name.value,
description: description.value
})
}
</script>
./pages/index.vue
<template>
<div>
<ul>
<li v-for="restaurant in restaurants.data" :key="restaurant.id">
{{ restaurant.attributes.name }}
<button @click="$router.push(`${$route.path}/restaurant/${restaurant.id}`)">Edit</button>
<button @click="deleteRestaurant(restaurant.id)">Delete</button>
</li>
</ul>
<div v-else>Loading...</div>
<nuxt-link :to="`${$route.path}/restaurant/create`">Create</nuxt-link>
</div>
</template>
<script setup>
const { data: restaurants, refresh } = await useAsyncData(
'restaurants',
() => $fetch("http://localhost:1337/api/restaurants")
)
const deleteRestaurant = async (restaurantId) => {
await $fetch(`http://localhost:1337/api/restaurants/${restaurantId}`, {
method: 'DELETE'
})
refresh()
}
</script>
./pages/restaurant/create.vue
<template>
<div>
<div><input type="text" v-model="restaurant.name" /></div>
<div><textarea v-model="restaurant.description"></textarea></div>
<button @click="createRestaurant();$router.go(-1)">Create</button>
<button @click="$router.go(-1)">Cancel</button>
{{ restaurant }}
</div>
</template>
<script setup>
const restaurant = ref({ name: "", description: "" })
const createRestaurant = async () => {
await $fetch("http://localhost:1337/api/restaurants", {
method: "POST",
body: {
data: {
name: restaurant.value.name,
description: restaurant.value.description
}
}
})
}
</script>
./pages/restaurant/[id].vue
<template>
<div>
<div><input type="text" v-model="restaurant.name" /></div>
<div><textarea v-model="restaurant.description"></textarea></div>
<button @click="updateRestaurant();$router.go(-1)">Update</button>
<button @click="$router.go(-1)">Cancel</button>
{{ restaurant }}
</div>
</template>
<script setup>
const route = useRoute()
const response = await $fetch(`http://localhost:1337/api/restaurants/${route.params.id}`)
const restaurant = ref(response.data.attributes)
const updateRestaurant = async () => {
await $fetch(`http://localhost:1337/api/restaurants/${route.params.id}`, {
method: "PUT",
body: {
data: {
name: restaurant.value.name,
description: restaurant.value.description
}
}
})
}
</script>