简介:该教程兼容pc+移动端,如只需一端,可忽略兼容部分教程,根据需要运行的客户端构建项目
访问https://codeload.github.com/nuxt/starter/tar.gz/refs/heads/v3,下载压缩报解压到项目下,或者运行npx nuxi@latest init vue_common,之前配置过vue环境的,最好更新下,开发工具webstrom建议用2023
yarn install 安装依赖
yarn dev -o 启动
2131
demo父级页面
//demo>test>index.vue
demo测试页
浏览器访问:http://localhost:3000/demo/test
//demo>test1>index.vue
demo测试页1
浏览器访问:http://localhost:3000/demo/test1
动态路由1:{{ $route.params.group }} - {{ $route.params.id }}
浏览器访问:http://localhost:3000/dynamicGroup/123
yarn add sass
/**
* 涉及全局px需要在此,定义样式,并在globals引用,用来兼容pc和移动,不用兼容可以直接写在 globals,也可以全局引入@import "globalsIndex"
*/
body{
font-size: $font_size
}
/**
* 涉及px单位的,需要做pc和移动端的兼容;不需要兼容,可去掉此代码;
*/
.pc{
@import "globalsIndex";
}
.mobile{
@import "globalsIndex";
}
$font_size: 14px;//基础字体大小
@import "./variable";
@import "./globals";
@import "./normalize";
@import "../font/iconfont.css";
export default defineNuxtConfig({
...
css: [
"@/assets/css/iframe.scss"
],
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "assets/css/variable.scss";',
}
}
}
},
...
})
export default defineNuxtConfig({
...
alias: {
"@img": "~assets/image/",
},
...
})
yarn add @pinia/nuxt --dev
export default defineNuxtConfig({
...
modules: ["@pinia/nuxt"], //配置Nuxt3的扩展的库
...
})
import { defineStore } from "pinia";
interface StoreInterface {
stroe: boolean;
}
const useStroe = defineStore("mobile", {
state: ():StoreInterface => {
return {
stroe: true,
};
},
actions: {
updateMobile:()=>{
return {
stroe: false
};
},
fetchHomeData:async ()=> {
},
},
getters: {
stroes: state => state.stroe,
}
});
export default useStroe
import { defineStore } from "pinia";
interface IsMobileInterface {
isMobile: boolean;
}
const useMobile = defineStore("mobile", {
state: ():IsMobileInterface => {
return {
isMobile: false,
};
}
});
export default useMobile
import useMobile from "@store/useMobile";
import {storeToRefs} from "pinia";
const mobileStore = useMobile();//静态值,不可以动态改变
let {isMobile} = storeToRefs(mobileStore); //可以动态改变,如:点击某个btn,改变值
const changeMobile = () => {
isMobile.value = true;
}
//app.vue
yarn add @pinia-plugin-persistedstate/nuxt --dev
export default defineNuxtConfig({
...
modules: [ //配置Nuxt3的扩展的库
"@pinia/nuxt",
'@pinia-plugin-persistedstate/nuxt',
],
...
})
//localStorage
import { defineStore } from "pinia"
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
}
},
persist: {
storage: persistedState.localStorage,
},
})
//sessionStorage
import { defineStore } from "pinia"
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
}
},
persist: {
storage: persistedState.sessionStorage,
},
})
//cookie
import { defineStore } from "pinia"
export const useStore = defineStore('main', {
state: () => {
return {
someState: 'hello pinia',
}
},
persist: {
storage: persistedState.cookiesWithOptions({
sameSite: 'strict',
}),
},
});
export default defineNuxtConfig({
...
modules: [
"@pinia/nuxt",
"@pinia-plugin-persistedstate/nuxt"
],
piniaPersistedstate: {
cookieOptions: {
sameSite: "strict",
},
storage: "localStorage"//默认储存方式
},
...
})
yarn add postcss-px-to-viewport-8-plugin --dev
export default defineNuxtConfig({
...
postcss: {
plugins: {
"postcss-px-to-viewport-8-plugin": {
viewportWidth: 375, // 视窗的宽度,对应的是我们设计稿的宽度
viewportHeight: 912, // 视窗的高度,对应的是我们设计稿的高度
unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数(很多时候无法整除)
viewportUnit: 'vw', // 指定需要转换成的视窗单位,建议使用vw
propList: ['*'],
selectorBlackList: [/^.pc/],
minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位,你也可以设置为你想要的值
mediaQuery: false, // 允许在媒体查询中转换`px`,
exclude: [/pc[\s\S]*.vue/,/element-plus/,/elementTheme.scss/], //设置忽略文件,用正则做目录名匹配
}
}
}
...
})
export default defineNuxtConfig({
...
app: {
head: {
title: "项目标题",
meta: [
{name: "description", content: "项目的重点信息描述--" },
{name: "keywords", content: "项目关键词" },
{name:"applicable-device", content:"pc,mobile"}, // 移动pc适配
],
link: [{
rel:"icon",
type: "image/x-icon",
href:"/new_favicon.ico"
}],
}
}
...
})
yarn add vant
yarn add @vant/nuxt --dev
export default defineNuxtConfig({
modules: [
"@vant/nuxt"
],
vant: { /** Options */ }
})
button
:root:root {
--van-primary-color: red;
}
//iframe.scss
@import "./vanTheme";
@import "./globals";
@import "./normalize";
@import "../font/iconfont.css";
yarn add element-plus
yarn add @element-plus/nuxt --dev
export default defineNuxtConfig({
...
modules: [
"@element-plus/nuxt"
],
elementPlus: { /** Options */ }
...
})
button
:root:root{
--el-color-primary: green;
}
//iframe.scss
@import "./elementTheme";
@import "./globals";
@import "./normalize";
@import "../font/iconfont.css";
3.编写兼容pc、移动端组件
//pc.scss
@import "index";
//mobile.scss
@import "index";
.button{
font-size: 14px;
height: 32px;
padding: 4px 15px;
border-radius: 6px;
}
export default defineNuxtConfig({
...
components: [{
path: '~/components/',
pathPrefix: false, //只根据名称使用组件
}],
...
})
一些在所有页面共享的默认布局
//app.vue
自定义布局
//app.vue
//index.vue
//index.vue
//index.vue
重写布局
当前页面
export default defineEventHandler(() => 'service demo')
浏览器:http://localhost:3000/routes
页面:await useFetch('/routes')
export default defineEventHandler(() => 'service api demo')
浏览器:http://localhost:3000/api/demo
页面:await useFetch('/api/demo')
//routes>routes.post.ts
export default defineEventHandler(() => 'service router post")
//api>demo.post.ts
export default defineEventHandler(() => 'service api post")
页面:await useFetch('/routes',{ method: 'post'})
页面:await useFetch('/api/demo',{ method: 'post'})
//routes>par>[name].post.ts
import {H3Event,H3EventContext} from "h3";
export default defineEventHandler((event:H3Event) => {
let params = event.context.params as H3EventContext;
return `service router post ${params.name}`
});
//api>[name].post.ts
import {H3Event,H3EventContext} from "h3";
export default defineEventHandler((event:H3Event) => {
let params = event.context.params as H3EventContext;
return `service api post ${params.name}`
});
页面:await useFetch('par/routerName',{ method: 'post'});
页面:await useFetch('/routerName',{ method: 'post'});
import { createRouter, defineEventHandler, useBase } from "h3";
const router = createRouter()
router.get('/slugGet', defineEventHandler(() => 'slugGet'))
router.post('/slugPost', defineEventHandler(() => 'slugPos'))
export default useBase('/api/slug', router.handler);
浏览器:http://localhost:3000/api/slug/slugGet
页面:await useFetch('/api/slug/slugGet');
页面:await useFetch('/api/slug/slugPost',{ method: 'post'});
import {H3Event, H3EventContext} from "h3";
export default defineEventHandler(async (event:H3Event) => {
const body = await readBody(event);
const query = getQuery(event);
let params = event.context.params as H3EventContext;
const config = useRuntimeConfig();
const cookies = parseCookies(event)
const id = parseInt(params.id) as number;
// if (!Number.isInteger(id)) {
// throw createError({
// statusCode: 400,
// statusMessage: "错误处理",
// })
// }
// setResponseStatus(200, '21321')
return {
text:`service router post ${params.name}`,
params,
body,
query,
config,
cookies
}
});
页面:await useFetch('api/apiName',{
method: 'post',
body: { test: 'body' },
query:{ test: 'query' }
});
export default defineEventHandler((event) => {
console.log('New request: ' + event.node.req.url)
})
//nuxt.config.ts
export default defineNuxtConfig(
...
nitro: {
storage: {
redis: {
driver: "redis",
port: 3000,
host: "localhost",
username: "",
password: "",
db: 0,
tls: {}
}
}
}
...
});
export default defineEventHandler(async (event) => {
const body = await readBody(event)
let params = event.context.params as H3EventContext;
await useStorage().setItem('redis:Storage', body)
return `service router post ${params.name}`
})
export default defineEventHandler(async (event) => {
const data = await useStorage().getItem('redis:Storage')
return data
});
页面:
const { data: resDataSuccess } = await useFetch('/api/apiName', {
method: 'post',
body: { text: 'storage' }
})
const { data: resData } = await useFetch('/api/demo')
yarn add axios
页面:import axios from "axios";
await axios.post("http://localhost:3000/api/apiName",{ test: 'axios' })
/**
* @description axios公共请求封装
* */
import axios, {AxiosResponse, InternalAxiosRequestConfig} from "axios";
/**
* @description 定义相关接口或者枚举
* */
//请求枚举
export enum MethodEnum {
Get='GET',
Post='POST'
}
//返回结果
export interface ResponseResultInterface {
Header:{},
Body: Body
}
//请求参数
export interface RequestInterface {
url:string,
params?:params,
method?:MethodEnum
}
/**
* 封装axios
* */
// 添加请求拦截器
axios.interceptors.request.use( (config:InternalAxiosRequestConfig)=>{
return config;
}, (error)=>{
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use( (response:AxiosResponse) => {
return response;
}, (error) => {
return Promise.reject(error);
});
/**
* @method useAxiosRequest axios请求封装
* @param requestPar { RequestInterface } 请求url
* @return Promise
* */
const useAxiosRequest= async (requestPar:RequestInterface):Promise => {
const requestResult:AxiosResponse = await axios({
method: requestPar.method || MethodEnum.Post,
url: requestPar.url,
data: requestPar.params
});
return requestResult.data as responseData;
};
export default useAxiosRequest;
/**
* @description useFetch请求封装
* */
import {FetchContext} from "ofetch";
import {_AsyncData} from "#app/composables/asyncData";
/**
* @description 定义相关接口或者枚举
* */
//请求枚举
export enum MethodEnum {
Get='GET',
Post='POST'
}
//返回结果
export interface ResponseResultInterface {
Header:{},
Body: Body
}
export interface RequestInterface{
url:string,
method?: MethodEnum,
params?: params
}
/**
* @method useRequest useFetch请求封装
* @param requestPar {RequestInterface} 请求参数
* */
const useRequest = async (requestPar:RequestInterface):Promise=>{
const requestResult:_AsyncData = await useFetch(requestPar.url,{
method:requestPar.method || MethodEnum.Post,
params:requestPar.params || {},
//请求拦截
onRequest(requestOption:FetchContext):void {
// options.headers = options.headers || {}
},
//错误请求拦截
onRequestError(RequestErrorOption:FetchContext):void {
// throw createError({
// statusCode: 500,
// statusMessage: reqUrl,
// message: '自己后端接口的报错信息',
// })
},
//响应拦截
onResponse(ResponseOption:FetchContext):void {
},
//响应错误拦截
onResponseError(responseErrorOption:FetchContext):void {
// throw createError({
// statusCode: 500,
// statusMessage: reqUrl,
// message: '自己后端接口的报错信息',
// })
}
});
return requestResult.data.value as responseData;
}
export default useRequest;
export default defineNuxtPlugin(nuxtApp => {
return {
provide: {
demo: (msg: string) => `demo ${msg}`
}
}
});
页面:
插件:{{ $demo('插件') }}
export default defineNuxtPlugin(nuxtApp => {
return {
provide: {
demo1: (msg: string) => `demo1 ${msg}`
}
}
});
export default defineNuxtPlugin(nuxtAp => { return { provide: { demo2: (msg: string) => `${nuxtApp.$demo1('demo2')} ${msg}` } } });
export default defineNuxtPlugin((nuxtApp) => {
// 客户端 & 服务端
nuxtApp.hook("app:created", (vueApp) => {
console.log("app:created");
});
// 服务端
nuxtApp.hook("app:beforeMount", (vueApp) => {
console.log("app:beforeMount");
});
// 客户端 & 服务端
nuxtApp.hook("vue:setup", () => {
console.log("vue:setup");
});
// 服务端
nuxtApp.hook("app:rendered", (renderContext) => {
console.log("app:rendered");
});
// 客户端
nuxtApp.hook("app:mounted", (vueApp) => {
console.log("app:mounted");
});
});
import {DirectiveBinding, VNode} from "@vue/runtime-core";
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.vueApp.directive('focus', {
// 在绑定元素的 attribute 或事件监听器被应用之前调用
created:(el)=>{},
// 在绑定元素的父组件挂载之前调用
beforeMount:(el)=>{},
// 在包含组件的 VNode 更新之前调用
beforeUpdate:(el)=>{},
// 在包含组件的 VNode 及其子组件的 VNode 更新之后调用
updated:(el)=>{},
// 在绑定元素的父组件卸载之前调用
beforeUnmount:(el)=>{},
// 卸载绑定元素的父组件时调用
unmounted:(el)=>{},
// 绑定元素的父组件被挂载时调用
mounted:(el)=>{
el.focus()
},
//渲染时向元素添加属性
getSSRProps:(binding:DirectiveBinding, vnode:VNode) =>{
return {
id:'test'
}
}
})
});
页面:
export default defineNuxtConfig({
...
imports: {
dirs:
"composables/**"
]
},
...
});
页面使用:const mobileStore = useMobile();//相比之前不需要在import导入
#开发环境配置
VITE_HOST=http://127.0.0.1:3000/ #本地请求ip+端口
VITE_PROXY=http://127.0.0.1 #需要代理的ip
VITE_PROXY_3002=3002 #需要代理的端口
import{loadEnv}from"vite";
/**
*@description定义env接口*/
interfaceENV_CONFIG{
host:string
host1:string
}
const envScript=(process.envasany).npm_lifecycle_script.split('');
const envName=envScript[envScript.length-1];//通过启动命令区分环境
const envData=loadEnv(envName,'env') as ENV_CONFIG|unknown;
export default defineNuxtConfig({
...
runtimeConfig: {
public: envData // 把env放入这个里面,通过useRuntimeConfig获取
},
vite: {
envDir: '~/env', // 指定env文件夹
},
...
});
页面:const envConfig = useRuntimeConfig();
package.json配置:"dev": "nuxt dev --mode dev",
import{getRequestHeaders, getRequestURL, H3Event, HTTPMethod} from "h3";
const {public: {
VITE_PROXY,
VITE_PROXY_3002
}} =useRuntimeConfig();
interfaceApiInterface{
[propName:string]:string
}
//把已有的ip和端口。组成请求的url
constapiUrlOption:ApiInterface ={
3002:`${VITE_PROXY}:${VITE_PROXY_3002}`
}
//请求路由配置,getArticles是后端提供的api
constapiRouter:ApiInterface ={
"/getArticles":`${apiUrlOption["3002"]}/getArticles`
};
export defaultdefineEventHandler(async (event:H3Event):Promise => {
const urlInfo:URL = getRequestURL(event);
const requestUrl:string =apiRouter[urlInfo.pathname];
if(requestUrl){
const method:HTTPMethod =getMethod(event);
// const query:QueryObject =getQuery(event);
const headers =getRequestHeaders(event);
const options: any = {
responseType: 'json',
}
options.headers = headers;
options.method = method;
if (method != 'GET') {
options.body = awaitreadBody(event);
}
return await $fetch(requestUrl,options);
}
});
页面:const envConfig:RuntimeConfig = useRuntimeConfig();
await useFetch(`${VITE_HOST}getArticles`)
server {
listen 9001;
server_name localhost;
# server_name btyhub.site, www.btyhub.site;
# ssl两个文件,放在 nginx的conf目录中
# ssl_certificate btyhub.site_bundle.pem;
# ssl_certificate_key btyhub.site.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# 代理到Next的服务,默认3000端口,也可以在start的时候指定
location / {
proxy_pass http://127.0.0.1:7000/;
}
}
{
"name": "nuxt-app",
"private": true,
"scripts": {
"start": "cross-env PORT=7000 HOST=127.0.0.1 node .output/server/index.mjs"
}
}
let exec = require("child_process").exec;
exec("yarn start", {windowsHide: true});