# install dependencies
$ npm install
# serve with hot reload at localhost:3000
$ npm run dev
# build for production and launch server
$ npm run build
$ npm run start
# generate static project
$ npm run generate
注意: 只能用 npm 来装依赖包,不能用yarn,会导致 ant design vue 的样式表类名变成hash值,不晓得为什么
一、asyncData
服务端调用接口,实现服务端渲染,调接口、给data赋值等,进入路由的时候就调用,
注意:无法调用
methods
中的方法
二、 fetch
- fetch 方法用于在渲染页面前填充应用的状态树(store)数据, 与 asyncData 方法类似,不同的是它不会设置组件的数据。
- 它会在组件每次加载前被调用(在服务端或切换至目标路由之前)。
三、 nuxt 引入 ant-design-vue
1、在 nuxt.config.js
中的 css 选项内配置
css: [
'ant-design-vue/dist/antd.css',
'@wangeditor/editor/dist/css/style.css',
{
src: 'assets/common.less',
lang: 'less'
}
]
2、在plugins
目录下新建antd-ui.js
import Vue from 'vue';
// 按需引用
import {
Button,
Table,
ConfigProvider,
message
} from 'ant-design-vue/lib'; // 按需引入组件
Vue.use(Button);
Vue.use(Table);
Vue.use(ConfigProvider);
Vue.prototype.$message = message;
3、在 nuxt.config.js
的 plugins
中配置插件
// 在plugins目录下添加的文件都需要在这里引入
plugins: [
'@/plugins/antd-ui'
]
4、 layouts/home.vue
中引入语言包
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN';
export default {
name: 'HomeLayout',
data () {
return {
locale: zhCN
};
}
};
5、 页面中使用
<template>
<div class="home-layout">
<a-config-provider :locale="locale">
<nuxt />
</a-config-provider>
</div>
</template>
四、nuxt 引入 axios
1. 在/plugins
目录下新建axios.js
import apis from '../apis';
export default function (context, inject) {
const server = context.$axios.create({
baseURL: context.$config.baseURL,
timeout: 5000,
headers: {
common: {
'Content-Type': 'application/json'
}
}
});
server.onRequest(config => {
return config;
});
server.onResponse(resp => {
// http状态码
if (resp.status === 200) {
// 业务状态码
if (resp.data && resp.data.code !== '200') {
if (process.client) {
context.store._vm.$message.error(resp.data.msg || '操作失败');
}
return resp.data;
}
return resp.data.data;
} else {
return null;
}
});
server.onError(error => {
console.error('onError---------', error.message);
if (process.client) {
context.store._vm.$message.error(error.message || '系统异常');
}
return Promise.reject(error.message || '系统异常');
});
// 给所有api注入 axios 实例
server.apis = apis(server);
// Inject to context as $api
inject('server', server);
}
2. nuxt.config.js
中 axios 相关配置
plugins: [
...
'@/plugins/axios'
],
modules: [
'@nuxtjs/style-resources',
'@nuxtjs/axios'
],
axios: {
credentials: true // 使用cookie
}
3. /apis/index.js
import user from './user';
export default (axios) => ({
user: user(axios)
});
4. apis/user.js
export default (axios) => ({
postMethod: (data, params = '') => {
return axios.post('/alive', data, { params });
},
checkAlive: (params) => {
return axios.get('/alive', { params });
},
objectList: (params) => {
return axios.get('/api/app/v440/objectList', { params });
}
});
5. 调用api
methods: {
async getObjectList () {
try {
const result = await this.$server.apis.user.objectList({
uid: '5aa01161fdf2161785de5',
family_code: '14893F342861057ACA31992DB6',
category_code: 'all',
limit: this.pagination.pageSize,
page: this.pagination.current,
darklayer: false
});
this.objectList = result.objects.items;
this.$message.success('操作成功');
} catch (e) {
console.error(e);
this.$message.error(e.msg || e.message);
}
},
}
五、部署到服务器
环境变量的配置得用
publicRuntimeConfig
1. 将项目代码推送至服务器指定目录
2. 服务器中,进入到项目根目录进行构建
npm run build:test # 构建测试环境
npm run build # 构建生产环境
package.json 中脚本配置
"build:test": "cross-env NODE_ENV=test nuxt build",
"build": "cross-env NODE_ENV=production nuxt build"
3. 添加 pm2
启动配置文件pm2.json / pm2-test.json
// pm2.json
{
"apps": [
{
"name": "NuxtAppTempl",
"exec_mode": "cluster",
"instances": "2",
"script": "./node_modules/nuxt/bin/nuxt.js",
"args": "start"
}
]
}
// pm2-test.json
{
"apps": [
{
"name": "NuxtAppTempl",
"exec_mode": "cluster",
"instances": "2",
"env": {
"NODE_ENV": "test" // 设置环境变量
},
"script": "./node_modules/nuxt/bin/nuxt.js",
"args": "start"
}
]
}
4. pm2
启动项目
pm2 start pm2.json
5. 配置 nginx
map $sent_http_content_type $expires {
"text/html" epoch;
"text/html; charset=utf-8" epoch;
default off;
}
server {
listen 80;
server_name www.mynuxt.com; # 配置域名
gzip on;
gzip_min_length 1k;
gzip_comp_level 9;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript;
gzip_vary on;
location / {
expires $expires;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 1m;
proxy_connect_timeout 1m;
proxy_pass http://127.0.0.1:3000; # set the address of the Node.js instance here
}
#charset koi8-r;
#access_log logs/host.access.log main;
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}