淺談前端nuxt(ssr)

SSR: 服務端渲染(Server Side Render),即:網頁是經過服務端渲染生成後輸出給客戶端。css

1、那爲何要使用SSR呢?

我用一句話理解的就是下降SPA(Single Page Application)首屏渲染的時間,解決SPA不利於SEO(Search Engine Optimization)的優化。vue

那Nuxt是什麼呢?跟SSR有什麼關係呢?node

Nuxt.js 是一個基於 Vue.js 的通用應用框架。webpack

經過對客戶端/服務端基礎架構的抽象組織,Nuxt.js 主要關注的是應用的 UI渲染。ios

咱們的目標是建立一個靈活的應用框架,你能夠基於它初始化新項目的基礎結構代碼,或者在已有 Node.js 項目中使用 Nuxt.js。git

Nuxt.js 預設了利用Vue.js開發服務端渲染的應用所須要的各類配置。github

除此以外,咱們還提供了一種命令叫:nuxt generate,爲基於 Vue.js 的應用提供生成對應的靜態站點的功能。web

咱們相信這個命令所提供的功能,是向開發集成各類微服務(microservices)的 Web 應用邁開的新一步。vuex

做爲框架,Nuxt.js 爲 客戶端/服務端 這種典型的應用架構模式提供了許多有用的特性,例如異步數據加載、中間件支持、佈局支持等。vue-cli

Nuxt.js是受到了React SSR框架Next.js的啓發,使用 Webpack 和 Node.js 進行封裝的基於Vue的SSR框架。

2、nuxt.js的優點

1)就是咱們無需爲了路由劃分而煩惱,你只須要按照對應的文件夾層級建立 .vue 文件就行。
2)無需考慮數據傳輸問題,nuxt 會在模板輸出以前異步請求數據(須要引入 axios 庫),並且對 vuex 有進一步的封裝。
3)內置了 webpack,省去了配置 webpack 的步驟,nuxt 會根據配置打包對應的文件。
4)中間件容許您定義一個自定義函數運行在一個頁面或一組頁面渲染以前。

3、開始Nuxt項目的搭建

1.首先根據官方網站教程建立一個項目。

爲了快速入門,Nuxt.js團隊建立了腳手架工具 create-nuxt-app

確保安裝了npx(npx在NPM版本5.2.0默認安裝了):

$ npx create-nuxt-app <項目名>

或者用yarn :

$ yarn create nuxt-app <項目名>

它會讓你進行一些選擇:

  1. 在集成的服務器端框架之間進行選擇:
  2. 選擇您喜歡的UI框架:
  3. 選擇你想要的Nuxt模式 (Universal or SPA)
  4. 添加 axios module 以輕鬆地將HTTP請求發送到您的應用程序中。
  5. 添加 EsLint 以在保存時代碼規範和錯誤檢查您的代碼。
  6. 添加 Prettier 以在保存時格式化/美化您的代碼。

當運行完時,它將安裝全部依賴項,所以下一步是啓動項目:

$ npm run dev

應用如今運行在 http://localhost:3000 上運行。

 

2.引入axios,封裝axios和請求api(使用的easy-mock請求模擬數據)

1) 安裝依賴:npm i axios -S

2) 新建一個文件夾service,存放axios及api相關文件。

3)service目錄下新建index.js(封裝axios)

 1 /**
 2  * Created by yuchen on 2019/2/20.
 3  */
 4 import axios from 'axios'
 5 import qs from 'qs'
 6 import config from './config'
 7 import {API, API_URL} from './api'
 8 
 9 if (process.server){
10   config.baseURL = `http://${process.env.HOST || 'localhost'} : ${process.env.PORT || 3000}`
11 }
12 
13 const service = axios.create(config)
14 
15 // POST 傳參序列化
16 service.interceptors.request.use(
17   config => {
18     if (config.method === 'post') config.data = qs.stringfy(config.data)
19     return config
20   },
21   error => {
22     return Promise.reject(error)
23   }
24 )
25 
26 // 返回結果處理
27 service.interceptors.response.use(
28   res => {
29     return res.data
30   },
31   error => {
32     return Promise.reject(error)
33   }
34 )
35 
36 
37 const get = (url) => {
38   let temp = API[url]
39   let URL = `${API_URL}${temp}`
40   return service({
41     method: 'get',
42     url:URL
43   })
44 
45 }
46 
47 const post = (url, params, showLoading) => {
48   let temp = API[url]
49   let URL = `${API_URL}${temp}`
50   axios.post(URL, params, {
51     showLoading: showLoading
52   })
53 }
54 
55 export default {
56  get
57 }
View Code

 4) 新建config.js自定義配置

 1 /**
 2  * Created by yuchen on 2019/2/20.
 3  */
 4 import http from 'http'
 5 import https from 'https'
 6 
 7 export default {
 8   // 自定義的請求頭
 9   headers: {
10     post: {
11       'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
12     },
13     'X-Requested-With': 'XMLHttpRequest'
14   },
15   // 超時設置
16   timeout: 10000,
17   // 跨域是否帶Token
18   withCredentials: true,
19   // 響應的數據格式 json / blob /document /arraybuffer / text / stream
20   responseType: 'json',
21   // 用於node.js
22   httpAgent: new http.Agent({
23     keepAlive: true
24   }),
25   httpsAgent: new https.Agent({
26     keepAlive: true
27   })
28 }
View Code

5) 新建api.js存放相關請求api(easy-mock模擬)

 1 /**
 2  * Created by yuchen on 2019/2/25.
 3  */
 4 let API_URL = 'https://easy-mock.com/mock'
 5 const API = {
 6   'mockTest':'/5c7387403b7ff2219057c6bb/example/mock'
 7 }
 8 export {
 9   API_URL,
10   API
11 }

 

6) 在plugins下新建http.js(掛載$http到vue上)

1 /**
2  * Created by yuchen on 2019/2/25.
3  */
4 import Vue from 'vue'
5 import http from '~/service/index'
6 Vue.prototype.$http = http
7 Vue.use(http)
View Code

7) 在nuxt.config.js下引入插件plugins下的http.js

1 /**
2  * Created by yuchen on 2019/2/25.
3  */
4 import Vue from 'vue'
5 import http from '~/service/index'
6 Vue.prototype.$http = http
7 Vue.use(http)
View Code

 

3.跨域處理

使用過 vue 的同窗,確定知道對於項目中的跨域,vue-cli 對 webpack 中的 proxy 選項進行了一層封裝。它暴露出來的是一個叫 proxyTable 的選項,是對 webpack 中的 proxy 和其三方插件 http-proxy-middleware 的一個整合。

不幸的 Nuxt 中沒有 proxyTable 這麼一個配置項來進行跨域的配置。固然幸運的是,在 Nuxt 中你能夠直接經過配置 http-proxy-middleware 來處理跨域。更幸運的是 Nuxt 官方提供了兩個包來處理 axios 跨域問題。

首先,進行安裝

npm i @nuxtjs/axios @nuxtjs/proxy -D

而後在 nuxt.config.js 文件裏進行配置

 1 modules: [
 2   '@nuxtjs/axios'
 3 ],
 4 axios: {
 5   proxy: true
 6 },
 7 proxy: {
 8   '/api': {
 9     target: 'xxx.target.com',
10     pathRewrite: { '^/api': '' }
11   }
12 }
View Code

 

4.同理引入第三方插件element-ui

在plugins下新建element-ui.js(可全局和按需引用),而後在nuxt.config.js引入

 1 /**
 2  * Created by yuchen on 2019/2/20.
 3  */
 4 import Vue from 'vue'
 5 import ElementUI from 'element-ui'
 6 import 'element-ui/lib/theme-chalk/index.css'
 7 
 8 Vue.use(ElementUI)
 9 
10 // import { Radio } from 'element-ui'
11 // Vue.component(Radio.name, Radio )
View Code

 

5.官方教程引入css預處理器less

styleResources

  • 類型: Object
  • 默認: {}

當您須要在頁面中注入一些變量和mixin而沒必要每次都導入它們時,這很是有用。

Nuxt.js 使用 https://github.com/nuxt-community/style-resources-module 來實現這種行爲。

您須要爲css預處理器指定要包含的 模式 / 路徑 : lesssassscss 或 stylus

您不能在此處使用路徑別名(~ 和 @),

:warning: You cannot use path aliases here (~ and @),你須要使用相對或絕對路徑。

安裝 style-resources:

$ yarn add @nuxtjs/style-resources

根據須要安裝:

  • SASS: $ yarn add sass-loader node-sass
  • LESS: $ yarn add less-loader less
  • Stylus: $ yarn add stylus-loader stylus

若是使用的npm,則變爲npm install less-loader less

修改 nuxt.config.js:

1   modules: [
2     '@nuxtjs/style-resources'
3   ],
4   styleResources:{
5     less:'./assets/common.less'
6   }

 

4、項目地址及Demo展現

此nuxt項目在腳手架新建的基礎上增長了axios,elemet-ui,less,跨域處理,路由nuxt會幫你建立對應的路由,你只須要在page建立對應層級文件。

項目地址傳送門:nuxt-ssr

 

相關文章
相關標籤/搜索