nuxt.js使用笔记

安装
yarn create nuxt-app my-project

中文文档

引用scss
yarn add node-sass sass-loader --save-dev

"node-sass": "^4.12.0",
"sass-loader": "^10.1.1"
  • vue页面中使用

  • 全局引用
// nuxt.config.js 
css: [
    '@/assets/style/index.scss' // scss文件所在路径
  ],

引用高德地图

  • 引入script
// nuxt.config.js 
script: [
    {src: 'http://webapi.amap.com/maps?v=1.3&key=**********' }
  ],
  • plugins下新建一个aMap.js
export default function MapLoader() {
  return new Promise((resolve, reject) => {
      // 全局对象如果存在地图直接将结果抛出
      if (window.AMap) {
          resolve(window.AMap)
      } else {
          // 创建script标签并放入cdn链接
          var script = document.createElement('script')
          script.type = 'text/javascript'
          script.async = true
          script.src = 'http://webapi.amap.com/maps?v=1.3&key=your key&callback=initAMap'
          script.onerror = reject
          document.head.appendChild(script)
      }
      window.initAMap = () => {
          // 注入相关插件
          window.AMap.plugin(['AMap.ToolBar', 'AMap.CircleEditor', 'AMap.PolyEditor'], function () {
              //异步同时加载多个插件
              var toolbar = new AMap.ToolBar();
              map.addControl(toolbar);
          });
          // 将结果抛出
          resolve(window.AMap)
      }
  })
}
  • vue页面使用
import MapLoader from '@/plugins/aMap' mounted() { let that = this MapLoader().then(AMap => { that.map = new AMap.Map('container', { center: [121.42, 31.2371], // [经度,纬度] resizeEnable: true, zoom: 17 }) // 矢量图形 var circle = new AMap.Circle({ center: new AMap.LngLat(121.42, 31.2371), // 圆心位置 radius: 100, // 圆半径 fillColor: '#3ebff191', // 圆形填充颜色 strokeColor: '#fff', // 描边颜色 strokeWeight: 2// 描边宽度 }) that.map.add(circle) }) },

生命周期

Nuxtvue的基础上对生命周期做了扩展:

export defualt {
  middleware(){ }, // 服务端
  validate(){ },  // 服务端
  asyncData(){ },  // 服务端
  fetch(){ },  // store数据加载
  beforeCreate(){ },  // 服务端和客户端都会执行
  created(){ },  //  服务端和客户端都会执行
  beforeMount(){ }, // 
  mounted(){ } // 客户端
}
  • asyncData(context)
    如果需要服务端渲染,首次渲染时一定要使用这个方法。它可以在渲染组件前异步获取数据。asyncData传入context参数,可以获取一些信息,如:
export default {
  asyncData(ctx){
    ctx.app   // 根实例
    ctx.route   // 路由实例
    ctx.params   // 路由参数
    ctx.query   // 路由问号后的参数
    ctx.error   // 错误处理方法
  }
}

使用这个方法时要注意,如果由于服务器或api错误导致无法渲染,就要做好容错机制,可以使用context.error方法。我们可以这样做:

async asyncData(ctx){
  try {
    throw new Error()
  } catch {
    ctx.error( {statusCode: 500, message: '服务器开小差了~'} ) // 这里的statusCode参数必须是http状态码
  }
}

head()

用于更新头部信息title/descripe等

export default {
head: {
    title: '文章页',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'keywords', name: 'keywords', content: '文章页的关键字' },
      { hid: 'description', name: 'description', content: '文章页的描述' }
    ],
  }
}

打包发布

yarn build  // 打包
yarn start  // 本地运行看是否可运行

package.json.nuxtstaticnuxt.config.js这四个文件上传到服务器,再在服务器运行:

yarn install
yarn start

使用二级路由时刷新路由与数据问题

目录结构

//目录结构
pages 
   product
      index.vue
   product.vue

在product.vue里



在index.vue里使用watchQuery来控制数据刷新

  watchQuery: true,
  watchQuery: ['id'], // 此id为路由里query里的属性
  async asyncData({ query }) {
    let [productInfo, carouselList] = await Promise.all([
      product_info(query),
      carousel_list({ type: 1 }),
    ])
    return {
      productInfo: productInfo.data,
      carouselList: carouselList.data,
    }
  },

切换页面不自动回到顶部问题

// nuxt.config.js 
router: {
    scrollBehavior(to, from, savedPosition) {
      return { x: 0, y: 0 }
    }
  }

使用pm2

安装

npm i -g pm2

启用nuxt项目(这个my-nuxt,就是项目名字)

pm2 start npm --name "my-nuxt" -- run start

常用pm2命令

pm2 list                   # 查看当前正在运行的进程
pm2 start all              # 启动所有应用
pm2 restart all            # 重启所有应用
pm2 stop all               # 停止所有的应用程序
pm2 delete all             # 关闭并删除所有应用
pm2 logs                   # 控制台显示所有日志 
pm2 start 0                # 启动 id为 0的指定应用程序
pm2 restart 0              # 重启 id为 0的指定应用程序
pm2 stop 0                 # 停止 id为 0的指定应用程序
pm2 delete 0               # 删除 id为 0的指定应用程序 
pm2 logs 0                 # 控制台显示编号为0的日志
pm2 show 0                 # 查看执行编号为0的进程
pm2 monit jsyfShopNuxt     # 监控名称为jsyfShopNuxt的进程

设置端口

// package.json
"config": {
    "nuxt": {
      "host": "0.0.0.0",
      "port":"8136"
    }
  }

你可能感兴趣的:(nuxt.js使用笔记)