# nuxt-site
**Repository Path**: jxmlearner/nuxt-site
## Basic Information
- **Project Name**: nuxt-site
- **Description**: 将vue企业站,用nuxt来重写一遍
- **Primary Language**: Unknown
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 11
- **Forks**: 2
- **Created**: 2020-01-10
- **Last Updated**: 2023-08-29
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# nuxt.js做企业站
## 一、 新建项目
1. `npx create-nuxt-app nuxt-site`
2. https://github.com/wmui/essay 该站是用nuxt开发的,可以学习参考
## 二、修改部分ESLint的规则
1. 关于`nuxt`报ESlint的错误,如:`Require self-closing on HTML elements (
) vue/html-self-closing`,解决方法:
```js
module.exports = {
root: true,
env: {
browser: true,
node: true
},
parserOptions: {
parser: 'babel-eslint'
},
extends: [
'@nuxtjs',
'plugin:nuxt/recommended'
],
// add your custom rules here
rules: {
'nuxt/no-cjs-in-config': 'off',
'vue/html-self-closing': ['error', {
'html': {
'void': 'never',
'normal': 'any',
'component': 'any'
},
'svg': 'always',
'math': 'always'
}],
'vue/html-indent': 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/html-self-closing': 'off',
'no-console': 'off',
'no-tabs': 'off',
'indent': ['off', 2],
'space-before-function-paren': 'off'
}
}
```
## 三、`Nuxt.js`中使用`scss`
1. 安装包:`yarn add -D node-sass sass-loader`
2. `nuxt.config.js`中配置样式路径
```js
css: [
{ src: '@/assets/style.scss', lang: 'scss' }
],
```
## 四、`Nuxt.js`中使用`swiper`
1. 安装: `yarn add vue-awesome-swiper`
2. 使用参考: https://blog.csdn.net/u013778905/article/details/85171723 https://www.jianshu.com/p/1cd904955cd2
3. 在 `plugins`文件夹下新建`vue-awesome-swiper.js`文件
```js
import Vue from 'vue'
import VueAwesomeSwiper from 'vue-awesome-swiper/dist/ssr'
Vue.use(VueAwesomeSwiper)
```
4. `nuxt.config.js`中配置插件
```js
css: [
'@/assets/css/swiper.css'
],
plugins: [
{ src: "~/plugins/vue-awesome-swiper", ssr: false }
],
```
5. 使用示例
```js
```
## 五、 路由
1. 修改默认的样式激活类
```js
router: {
//linkActiveClass: 'active',
linkExactActiveClass: 'active'
},
```
## 六、 `nuxt.config.js`引入第三方`js`
```js
head: {
script: [
{ src: 'http://api.map.baidu.com/api?v=2.0&ak=kmxI7Hj2rGxxScm8OG4qS7sYIWzKo8QN' }
]
}
```
+ 加载百度地图
```js
export default {
components: {
Bread
},
mounted() {
this.loadMap()
},
methods: {
loadMap() {
var map = new BMap.Map(this.$refs.map)
var point = new BMap.Point(121.496398, 31.24412)
map.centerAndZoom(point, 15) // 初始化地图,设置中心点坐标和地图级别
map.addControl(new BMap.NavigationControl())
map.addControl(new BMap.MapTypeControl()) // 添加地图类型控件
map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
var marker = new BMap.Marker(point) // 创建标注
map.addOverlay(marker)
var opts = {
width: 200, // 信息窗口宽度
height: 100, // 信息窗口高度
title: '苏州润勒克五金工具有限公司', // 信息窗口标题
enableMessage: false, // 设置允许信息窗发送短信
message: '江苏苏州工业园港田路99号港田工业坊17幢二楼单元'
}
var infoWindow = new BMap.InfoWindow(
'地址:江苏苏州工业园港田路99号港田工业坊17幢二楼单元',
opts
) // 创建信息窗口对象
marker.addEventListener('click', function() {
map.openInfoWindow(infoWindow, point) // 开启信息窗口
})
map.openInfoWindow(infoWindow, point) // 开启信息窗口
}
}
}
```
## `axios`请求数据
1. 根目录下新建`config.js`
```js
let apiaddr = '/api'
export {
apiaddr
}
```
2. `nuxt.config.js`中配置反向代理
参考:https://blog.csdn.net/sinat_35538827/article/details/84032169
https://www.cnblogs.com/wang715100018066/p/10655457.html
```js
```
## 七、`nuxt.js`中使用`vuex`状态树
> 在`nuxt`中使用`vuex`跟传统在`vue`中使用`vuex`有小小差别,首先nuxt已经集成了`vuex`,不需要我们进行二次安装,直接引用就好,在默认`nuxt`的框架模板下有一个`store`的文件夹,就是我们用来存放`vuex`的地方
+ `nuxt`支持两种使用方式
- 普通方式:`store/index.js` 返回一个 `Vuex.Store` 实例
- 模块方式:`store` 目录下的每个 .js 文件会被转换成为状态树指定命名的子模块 (当然,index 是根模块,相当于设置了namespaced: true)
1. 参考官方文档 https://zh.nuxtjs.org/guide/vuex-store 及 https://blog.csdn.net/qq_19671173/article/details/90759431
https://www.cnblogs.com/zhangshuda/p/8241692.html
2. store
```js
import api from '../api'
import { htmlDecodeByRegExp } from '../assets/js/utils'
import { loadCompanyInfo, loadProductCategory } from './mutation-types'
export const state = () => ({
companyInfo: {
id: 0,
companyName: '企业站DEMO',
tel: '138********',
address: '广东省深圳市南山区',
contact: '江**',
mobile: '12345644564',
zipCode: '518000',
email: '410958040@qq.com',
QQ: '',
QRCode: '',
desc: '',
content: '',
copyRight: 'MIT Licensed | Copyright © 2019-present 江学美'
},
categoryList: []
})
export const getters = {
htmlContent(state) {
return htmlDecodeByRegExp(state.companyInfo.content)
}
}
export const mutations = {
[loadCompanyInfo](state, payload) {
state.companyInfo = Object.assign({}, payload.siteInfo)
},
[loadProductCategory](state, payload) {
state.categoryList = [...payload.cates]
}
}
export const actions = {
async nuxtServerInit({ dispatch }) {
await Promise.all([
dispatch(loadCompanyInfo),
dispatch(loadProductCategory)
])
},
async [loadCompanyInfo](context) { // 加载企业站的信息存储在state中
try {
const siteInfo = await api.siteinfo()
// console.log('获取企业信息', siteInfo.data)
if (siteInfo.data.errorCode === 0) {
context.commit({
type: loadCompanyInfo,
siteInfo: siteInfo.data.data
})
}
} catch (error) { // 这里的错误是会显示在Server端
console.log(error)
}
},
async [loadProductCategory](context) { // 加载产品分类列表
try {
const resData = await api.productcate()
if (resData.data.errorCode === 0) {
context.commit({
type: loadProductCategory,
cates: resData.data.data
})
}
} catch (error) {
console.log(error)
}
}
}
```
## 八、 nuxt.js中使用fetch时的注意点
1. 文档地址: https://zh.nuxtjs.org/api/pages-fetch
2. fetch 方法用于在渲染页面前填充应用的状态树(store)数据, 与 asyncData 方法类似,不同的是它不会设置组件的数据。如果页面组件设置了 fetch 方法,它会在组件每次加载前被调用(在服务端或切换至目标路由之前)
3. 从上面可以看出,fetch会分别在服务端和 切换路由(客户端)时调用,这里要分别处理
```js
import Vue from 'vue'
import httpCreator from '../assets/js/common-http'
import { ajaxApiAddr } from '@/config'
const isServer = Vue.prototype.$isServer
/*
如果是 vuex的 nuxtServerInit 使用 http
如果是页面的fetch(){} 是服务端使用 http://localhost:8888完整地址,如果是客户端 使用 /api 基地址(有配置proxy) -- 通过 Vue.prototype.$isServer判断
*/
const http = isServer ? httpCreator() : httpCreator(ajaxApiAddr)
// 获取轮播图
function focus () {
return new Promise((resolve, reject) => {
http.get('/focus').then(resolve).catch(reject)
})
}
```
## 九、 `element-ui`修改成按需加载
1. `cnpm install babel-plugin-component -D`
2. 修改 `plugins/element-ui.js`
```js
import Vue from 'vue'
import { Pagination } from 'element-ui'
import locale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(Pagination, { locale })
```
3. 修改 `nuxt.config.js`的`build`配置项
```js
build: {
babel: {
plugins: [
['component', {
'libraryName': 'element-ui',
'styleLibraryName': 'theme-chalk'
}]
]
},
// transpile: [/^element-ui/],
/*
** You can extend webpack config here
*/
extend (config, ctx) {
}
}
```
## 十、当直接访问 `/detail`没有传`id`时直接重定向到`/product`页面
```js
```
## 十一、nuxt部署
参考: http://www.imooc.com/article/294271
1. 首先在 `package.json`中增加一条`server`命令,供部署时启动
```js
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"server": "nuxt start",
"generate": "nuxt generate",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore ."
},
```
其实也完全可以将`package.json`中的命令替换成下面的, 这样更简洁 (注意此时后续再启动就是 npm run start, 也就是用 nuxt start来启动)
```js
{
...
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
}
}
```
2. 执行 `npm run build`, 再将 `.nuxt`文件夹、`package.json` 及`nuxt.config.js` 复制到部署目录, 安装依赖包`cnpm i --production`, 最后启动:`npm run start`
3. 使用`pm2`管理应用
```shell
cnpm install -g pm2
# 在线上目录的文件夹中另起一个cmd 执行
pm2 start npm --name "nuxtsite" run start
# --name "nuxtsite"是启动的服务名称 run start是配置的命令
```
4. 上面部署时注意在 `nuxt.config.js`中配置一下服务器的端口和`host`
```js
server: {
port: 8000, // default: 3000
host: '0.0.0.0' // default: localhost,
}
```
+ 如果项目不是根路径还需要配置`router`
```js
module.exports = {
router: {
base: '/app/'
}
}
```
5. 部署到`nginx`下
```shell
http {
upstream nodenuxt {
server 127.0.0.1:8000;
keepalive 64;
}
server {
listen 8011;
location / {
proxy_pass http://nodenuxt;
}
}
}
```
6. 部署https: https://www.lzzj.online/articleDetail/35
7. 用`@nuxtjs/dotenv`来处理配置
+ 参考: https://www.jianshu.com/p/c132150fc82f
+ 安装: `cnpm install --save-dev @nuxtjs/dotenv`
+ 配置 `nuxt.config.js`
```js
export default {
buildModules: [
// With options
['@nuxtjs/dotenv', { /* module options */ }]
]
}
```
+ 根目录下新建`.env`文件
```
apiaddr = 'http://localhost:8888'
ajaxApiAddr = '/api'
```