官网:https://nuxt.com.cn/
配置环境变量
1.根目录下新建文件.env.development
和.env.production
,当然文件.env.xxx
都行,只要和后面对应上即可;
2.文件中增加全局环境变量,例如:PUBLIC_API_BASE=https://api.com
;
3.nuxt.config.ts
配置文件增加配置项:
1 2 3 4 5 6 7 8
| export default defineNuxtConfig({ runtimeConfig: { apiKey: '', public: { baseURL: process.env.PUBLIC_API_BASE } }, })
|
4.引用环境变量:
1
| useRuntimeConfig().public.baseURL
|
配置api代理,解决跨域
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| export default defineNuxtConfig({ nitro: { devProxy: { "/api": { target: "http://192.168.1.1", changeOrigin: true, prependPath: true, }, }, routeRules: { '/api/**': { proxy: 'http://192.168.1.1/**' } } }, })
|
封装api请求方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
export const $http = async (obj) => { try { const res = await useFetch( (obj.baseURL ?? useRuntimeConfig().public.baseURL) + obj.url, { method: obj.method ?? "GET", query: obj?.query ?? null, body: obj?.body ?? null, onRequest({ request, options }) { options.headers = options.headers || {} }, onRequestError({ request, options, error }) { console.warn('Request Error'); }, onResponse({ request, response, options }) { }, onResponseError({ request, response, options }) { message.warning('Request Error'); } }, ) if (res.status.value === "success") { return Promise.resolve(res.data.value) } else { throw new Error(res.error) } } catch (err) { console.log(err) } }
|
useFetch
适合在ssr中使用,如果是在ssg中使用,用$fetch
最佳,参数都相同,改个名即可,如果后面想转ssr,再改名就可以了
静态资源
静态资源(如图片)放在public
目录下,没有新建一个,引用时直接/demo.png
即可。
useState全局共享状态
1 2 3 4 5 6 7 8
| const useCityName = (id) => { return useState("commonCityName", () => id); };
const change = () => { const cityName = useCityName(); cityName.value = v.city_name; }
|
在不同端获取数据
1 2 3 4 5 6 7 8
| const { article } = await useFetch('api/article')
const { pending, data: posts } = useFetch('/api/comments', { lazy: true, server: false })
|
要注意的是,如果使用的预渲染,水合之前执行的数据,img图片会有缓存,所以如果是经常变动的数据,不要使用这种方式请求数据;
服务端渲染(ssr)相关配置
- 新建文件
ecosystem.config.js
,并填写以下代码:1 2 3 4 5 6 7 8 9 10 11 12
| module.exports = { apps: [ { name: 'NuxtAppName', port: '8921', path : "服务器IP", exec_mode: 'cluster', instances: 'max', script: './.output/server/index.mjs' } ] }
|
- 安装pm2
- 在服务器项目目录下运行