编写接口
~/server/api/homeInfo.get.ts
export default defineEventHandler((event) => {
return {
code: 200,
data: {
name: 'hello world'
}
}
})
服务端有一些方法可以快速获取请求常见字段:
- getQuery(event)
- getMethod(event)
- await readBody(event)
- await readRawBody(event)
const {data} = await useFetch('/api/homeInfo', {
method: 'GET'
})
console.log(data)
设置获取 cookie (client and server):
全局状态共享
useState
- 在composables目录下创建一个模块,如:composables/states.ts
- 在states.ts中使用useState定义需全局共享状态,并导出(默认导出共享文件名,否则直接使用函数名)
- 在组件中导入states.ts导出的全局状态
~/composables/useCounter.ts
export default function () {
return useState('counter', () => 10)
}
// 或者
export const useCounter = () => {
return useState('counter', () => 10)
}
const count = useCounter()
console.log(count.value)
- useState只能用在setup函数和Lifecycle Hooks中
- useState不支持classes,functions or symbols类型,因为这些类型不支持序列化
Pinia
@pinia/nuxt会处理state 同步问题,比如不需要关心序列化或XSS攻击等问题。
安装:
npm i pinia --legacy-peer-deps
npm i @pinia/nuxt
nuxt.config.ts
export default defineNuxtConfig({
compatibilityDate: '2024-04-03',
devtools: {enabled: true},
modules: [
'@pinia/nuxt',
]
});
~/store/home.ts
export const useHomeStore = defineStore('home', {
state: () => {
return {
count: 0
}
},
actions: {
increment() {
this.count++
},
async fetchData() {
await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
}
}
})
const homeStore = useHomeStore()
const {count} = storeToRefs(homeStore)
console.log(count.value)