这是我参与「第五届青训营 」伴学笔记创作活动的第 13 天
NuxtJs简单上手
特点
对标React的Next.js
为什么使用Nuxt.js?
- SSR(服务端渲染)的页面初始加载时间显然优于单页首屏渲染
- 可以方便的对 SEO 进行管理
- 无需配置页面路由,内置 vue-rouer,自动依据 pages 目录结构生成对应路由配置
- 便捷的 HTML 头部标签管理(vue-meta)
- 项目结构自动代码分层
- 支持静态化
栗子:爱奇艺官网
创建和初始化项目
www.nuxtjs.org.cn/getting-sta…
yarn create nuxt-app + 项目名 Nuxt2
Nuxt 3:
npx nuxi init + 项目名
yarn // npm i
Pug有它本身的缺点——可移植性差,调试困难,性能并不出色,但使用它可以加快开发效率juejin.cn/post/701116…
To get started:
cd vue-ssr
yarn dev
To build & start for production:
cd vue-ssr
yarn build
yarn start
yarn dev
骚啊!
Nuxt2 的 Nuxt.config.js
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'vue-ssr',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/typescript
'@nuxt/typescript-build',
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
],
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
}
}
Nuxt3 的 Nuxt.config.js
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({})
Nuxt2 简单操作
配置路由
直接在pages中写即可访问,映射路由、组件名即是路由地址,二级路由同理,默认寻找index,不要重名,动态路由:如果带参数如user/1 可以新建_id.vue或者 [id] .vue ,并可以添加路由匹配限制,获取参数类似Vue。
export default {
validate({ params }) {
// 必须是number类型
return /^\d+$/.test(params.id)
}
}
路由参数获取:$route.params.xx、$route.query.xx
路由跳转:NuxtLink标签和router一样to="{path:完整路径}",
或者是 函数式:navigateto({path...})、需要设置根元素、与Vue3的小bug
使用~替代@、在最外层新建public文件夹,该文件夹是网站根目录,以/都会映射到该文件夹下
异步加载数据
asyncData
axios拦截
import axios from 'axios'
const myaxios = axios.create({
// ...
})
myaxios.interceptors.response.use(
function (response) {
return response.data
},
function (error) {
// ...
}
)
promise 和 await async
export default {
asyncData({ params }) {
return axios.get(`https://my-api/posts/${params.id}`).then(res => {
return { title: res.data.title }
})
}
}
// await async
export default {
async asyncData({ params }) {
const { data } = await axios.get(`https://my-api/posts/${params.id}`)
return { title: data.title }
}
}
公共模板布局
在layouts文件夹下的vue会展示在所有页面,可以在export defulat内使用 layout: "模板"选择使用,
如果不指定那就是layouts文件夹下defulat模块。
// layouts下格式
<template>
<div> lay <nuxt /> <div>
</template>
// 选择使用
layout (context) {
return "模板";
}
Nuxt3 简单使用
www.nuxtjs.org.cn/usage/data-…
js、css、title
在组件中使用xx,显示网站地址栏title ssr形式,或者使用useHead。