一、创建项目
1、npm i -g create-nuxt-app 2、create-nuxt-app myproject
二、知识点
1、目录结构
2、路由
* layouts下的default.vue为根组件 * <Nuxt/>(一级路由)或<Nuxt-child/>(嵌套路由)相当于<router-view/> 路由例子:目录路径 -> 路由路径 pages/index.vue -> / pages/aaa.vue -> /aaa pages/_aaa.vue -> /:aaa pages/aaa/index.vue -> /aaa
3、中间件
a、middleware下新建redirect.js文件
export default function ({isHMR, app, store, route, params, error, redirect}) { if (isHMR) { return } if (route.fullPath === "/") { return redirect("/center"); } }
b、nuxt.config.js配置
export default { router: { middleware: "redirect" }, //... }
4、视图
a、layouts下新建temp.vue
<template> <div> temp <Nuxt></Nuxt> </div> </template> <script> export default { name: "temp" } </script> <style scoped> </style>
b、pages下新建detail.vue
<template> <div> detail </div> </template> <script> export default { name: "detail", layout: "temp" } </script> <style scoped> </style>
5、生命周期
<template> <div class="container"> {{aaa}} </div> </template> <script> export default { beforeCreate() { this.aaa = "beforeCreate"//1 }, data() { return { aaa: "data"//2 } }, async asyncData() { return { aaa: "asyncData"//3 } }, created() { this.aaa = "created"//4,这里可以显示在源码中 }, mounted() { this.aaa = "mounted"//5 } } </script> <style> </style>
6、asyncData
async asyncData({isDev, route, store, env, params, query, req, res, redirect, error}) { //1、不能使用this和window //2、只在浏览器刷新或浏览器地址栏输入路径跳转时在服务端运行 //3、process.server全局变量:为true时表示在服务端,为false时表示在客户端 return {} },
三、打包发布
1、项目运行需要node环境
2、npm run build后复制【.nuxt、nuxt.config.js、static、package.json】至服务器
3、npm run start
* nohup npm run start &:后台方式运行
* exit:退出
* ps -ef|grep node:查看进程,第二列为进程号
* kill -9 进程号1 进程号2:杀死进程,cross-env NODE_ENV=prod nuxt start和nuxt start启动的进程
4、配置nginx.conf,然后nginx -s reload
server { listen 80; server_name www.dingcaiyan.com; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_pass http://127.0.0.1:3000; } }