0%

Nuxt.js 服务端渲染

什么是服务端渲染?

服务端渲染 (SSR) 在服务器生成 HTML,提高首屏加载速度和 SEO。

Nuxt.js 简介

Nuxt.js 是基于 Vue.js 的 SSR 框架,简化 SSR 开发。

安装

1
npx create-nuxt-app my-app

项目结构

1
2
3
4
5
6
7
8
9
pages/
index.vue
about.vue
components/
Header.vue
layouts/
default.vue
store/
index.js

页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- pages/index.vue -->
<template>
<div>
<h1>{{ title }}</h1>
<p>Welcome to Nuxt.js!</p>
</div>
</template>

<script>
export default {
data() {
return {
title: 'Home Page'
}
},
head() {
return {
title: this.title
}
}
}
</script>

路由

Nuxt.js 自动生成路由。pages/ 下的文件对应路由。

异步数据

1
2
3
4
5
6
export default {
async asyncData({ params }) {
const { data } = await axios.get(`https://api.example.com/posts/${params.id}`)
return { post: data }
}
}

状态管理

使用 Vuex 或 Pinia。

插件

1
2
3
4
5
// plugins/vue-notifications.js
import Vue from 'vue'
import VueNotifications from 'vue-notifications'

Vue.use(VueNotifications)

部署

1
2
npm run build
npm run start

总结

Nuxt.js 让 SSR 开发变得简单。适合需要 SEO 和首屏性能的应用。官方文档很详细,多实践。