Nuxt2.js
服务端生命周期
1.nuxtServerInit(nuxt中第一个运行的生命周期)
2.RouteMiddleware(第二个:中间键,路由导航守卫)
2-1 全局
在nuxt.config.js文件中的export default下
router:{
// 定义一个名称
middleware:'auth'
}
在项目文件中新建一个文件夹middleware中再新建一个对应在配置文件中起的名字(auth)的js文件
项目/middleware/auth.js
export default function({store,route,redirect,params,req,res}){
// 判断是否有token(就是是否登陆了,如果没有就跳转到指定的页面去)
let token = store.state.token
if(!token){
redirect('/list')
}
console.log('middleware')
}
2-2 局部
在要使用的页面中js中的export default配置个
middleware:'auth'
3.validate() 是用来校验url参数符不符合
validate({params,query}){
// 可以拿到参数信息
console.log('validate',params.id);
// 如果不返回true就会报错,页面就会跳转到404的页面
return true
}
4.asyncData()
asyncData方法会在组件(限于页面组件)每次加载之前被调用。它可以在服务端或路由更新之前被调用。在这个方法被调用的时候,第一个参数被设定为当前页面的上下文对象,你可以利用 asyncData方法来获取数据并返回给当前组件。
在components文件中的组件使用不了,fetch就都可
export default Vue.extend({
name: "IndexPage",
async asyncData({$axios}) {
const res = await $axios.$get("http://localhost:5000");
return {content: res.content};
},
data() {
return {
content: "",
};
},
});
</script>
5.fetch
fetch 方法用于在渲染页面前填充应用的状态树(store)数据, 与 asyncData 方法类似,不同的是它不会设置组件的数据。
如果页面组件设置了 fetch 方法,它会在组件每次加载前被调用(在服务端或切换至目标路由之前)。
asyncData在components文件中的组件使用不了,fetch就都可
在fetch中不能使用context,如果你使用了context参数,那么就会被视为旧版fetch。
如果你要使用context,那么推荐你使用asyncData或者匿名中间件
async fetch() {
// 从this中获取$axios而不是从context中获取
const res = await this.$axios.$get("http://localhost:5000");
// 这里界面上就能正确的渲染出数据
this.content = res.content;
}
服务端和客户端共有的生命周期
beforeCreate
created
客户端生命周期(Vue的生命周期)
context上下文
属性字段 | 类型 | 可用 | 描述 |
---|---|---|---|
app | Vue 根实例 | 客户端 & 服务端 | 包含所有插件的 Vue 根实例。例如:在使用 axios 的时候,你想获取 $axios 可以直接通过 context.app.$axios 来获取 |
isClient | Boolean | 客户端 & 服务端 | 是否来自客户端渲染(废弃。请使用 process.client ) |
isServer | Boolean | 客户端 & 服务端 | 是否来自服务端渲染(废弃。请使用 process.server ) |
isStatic | Boolean | 客户端 & 服务端 | 是否来自 nuxt generate 静态化(预渲染)(废弃。请使用 process.static ) |
isDev | Boolean | 客户端 & 服务端 | 是否是开发 dev 模式,在生产环境的数据缓存中用到 |
isHMR | Boolean | 客户端 & 服务端 | 是否是通过模块热替换 webpack hot module replacement (仅在客户端以 dev 模式) |
route | Vue Router 路由 | 客户端 & 服务端 | Vue Router 路由实例 |
store | Vuex 数据 | 客户端 & 服务端 | Vuex.Store 实例。只有vuex 数据流存在相关配置时可用 |
env | Object | 客户端 & 服务端 | nuxt.config.js 中配置的环境变量,见 环境变量 api |
params | Object | 客户端 & 服务端 | route.params 的别名 |
query | Object | 客户端 & 服务端 | route.query 的别名 |
req | http.Request | 服务端 | Node.js API 的 Request 对象。如果 Nuxt 以中间件形式使用的话,这个对象就根据你所使用的框架而定。nuxt generate 不可用 |
res | http.Response | 服务端 | Node.js API 的 Response 对象。如果 Nuxt 以中间件形式使用的话,这个对象就根据你所使用的框架而定。nuxt generate 不可用 |
redirect | Function | 客户端 & 服务端 | 用这个方法重定向用户请求到另一个路由。状态码在服务端被使用,默认 302 redirect([status,] path [, query]) |
error | Function | 客户端 & 服务端 | 用这个方法展示错误页:error(params) 。params 参数应该包含 statusCode 和 message 字段 |
nuxtState | Object | 客户端 | Nuxt 状态,在使用 beforeNuxtRender 之前,用于客户端获取 Nuxt 状态,仅在 universal 模式下可用 |
beforeNuxtRender(fn) | Function | 服务端 | 使用此方法更新 __NUXT__ 在客户端呈现的变量,fn 调用 (可以是异步) { Components, nuxtState } ,参考 示例 |
关于路由的事
路由:
1.可以使用nuxt 自带的自动生成路由表的功能。
2.可以使用插件来像vue项目中一样自己配置router.js
//1.安装插件
npm i @nuxtjs/router
//2.nuxt.config.js:配置
modules:[
'@nuxtjs/router'
]
//3.在项目根目录下设置router.js
//router.js
import Vue from 'vue'
import Router from 'vue-router'
import MyPage from '~/components/my-page'
Vue.use(Router)
export function createRouter() {
return new Router({
mode: 'history',
routes: [
{
path: '/',
component: MyPage,
beforeEnter: (to, from) => {
// reject the navigation
return false
},
}
]
})
}
关于路由导航守卫:
1.使用nuxt自带的middleware中间件功能实现
全局和局部中间件。
2.使用plugins来实现
// nuxt.config.js 中配置
//项目根目录新增plugins文件夹
plugins:[
'~/plugins/router.js'
]
// '~/plugins/router.js':
export default ({app})=>{
console.log(app.route.beforeEach)
}
服务端的不能使用客户端的localStorage 和 cookie 解决方案:
参考 cookie-universal-nuxt 插件 :https://www.npmjs.com/package/cookie-universal-nuxt
// 1. 安装
npm i --save cookie-universal-nuxt
//2.nuxt.config.js 配置
modules: [
// Simple usage
'cookie-universal-nuxt',
// With options
// ['cookie-universal-nuxt', { alias: 'cookiz' }],
]
//3. 正常使用就行
this.$cookies.set()
this.$cookies.get()
set(name, value, opts)
setAll(cookieArray)
get(name, opts)
getAll(opts)
remove(name, opts)
removeAll(opts)
nodeCookie
head的配置
全局(对象)
//nuxt.config.js中配置
head: {
title: 'mydemos11',
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' }],
},
页面中(函数返回的形式)
head(){
return{
title: 'mydemos11',
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' }],
}
}
全局css样式引入
// 创建css文件
// nuxt.config.js中配置
css: ['~assets/css/global.css'],
全局plugins
// 创建 plugins文件夹
//nuxt.config.js中配置
plugins:[
'~/plugins/aaa.js'
]
跨域问题解决
// 安装插件
npm install @nuxtjs/proxy -S
// nuxt.config.js 配置
modules:[
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
axios:{
// 是否可以跨域
proxy:true,
retry:{retries:3},
baseUrl:'xxx'
},
proxy:{
'/api':{
target:'http://cxxxxxx',
pathRewrite:{
'^/api':''
}
}
}
Loading样式
1.可以在nuxt.config.js中设置是否开启loading效果
-
设置loading效果
loading: { color: 'blue', height: '5px' }
3.自定义loading组件
// nuxt.config.js loading: '~/components/loading.vue'
<template lang="html"> <div class="loading-page" v-if="loading"> <p>Loading...</p> </div> </template> <script> export default { data: () => ({ loading: false }), methods: { start() { this.loading = true }, finish() { this.loading = false } } } </script> <style scoped> .loading-page { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); text-align: center; padding-top: 200px; font-size: 30px; font-family: sans-serif; } </style>