关于vue.js:nuxtjs快速上手nuxt2

4次阅读

共计 4240 个字符,预计需要花费 11 分钟才能阅读完成。

nuxtjs 疾速上手(nuxt2)

提醒:本篇文章是博主观看 b 站 up 主前端 aka 老师视频学习整顿的文章
视频指路:《CMS 全栈我的项目》系列九:Nuxt+ElementUI
nuxtjs 官网(nuxt2):NuxtJS

前言

提醒:本篇文章为 nuxt2:

本篇文章能够带你疾速搭建一个简略的 Nuxt.js 我的项目,Nuxt.js 是基于 Vue.js 的通用利用框架,Nuxt.js 预设了利用 Vue.js 开发 服务端渲染(SSR) 的利用所须要的各种配置,文章简要叙述 Nuxt.js 的根底性能,能够疾速上手 Nuxt!

提醒:以下是本篇文章正文内容,上面案例可供参考

一、疾速生成 nuxt 我的项目

运行 create-nuxt-app

确保装置了 npx (npx 在 NPM 版本 5.2.0 默认装置了):
npx create-nuxt-app < 我的项目名 >
或者用 yarn:yarn create nuxt-app < 我的项目名 >

二、nuxtjs 配置 IP 与端口

开发中常常会遇到端口被占用或者指定 IP 的状况。咱们须要在根目录下的 package.json 里对 config 项进行配置。比方当初咱们想把 IP 配置成 127.0.0.1,端口设置 8080

{
    ...,
    "config": {
        "nuxt": {
          "host": "127.0.0.1",
          "port": "8080"
        }
        // 或者
        "nuxt": {
          "host": "0.0.0.0",
          "port": "80"
        }
    }
} 

三、在 nuxt 中应用 less

  1. 装置 less 和 指定版本的 less-loader

    npm install less less-loader@7.0.0 --save-dev
  2. 全局款式文件
  3. static 目录中创立 base.less 文件,用来写全局款式。而后关上 nuxt.config.js 并找到 css

    css: [
     'element-ui/lib/theme-chalk/index.css',
         '~/static/base.less'    // 全局款式增加在此处
    ], 
  4. 组件内款式

    <style scoped lang="less">
    @bgColor: #f00;
    .el-container {
      width: 100%;
      height: 100%;
    
      .el-main {
     color: @bgColor;
     height: 100%;
     padding: 0;
      }
    }
    </style>

四、nuxtjs 中我的项目革除默认款式

  1. 关上 reset-css 的 npm 网站,轻易拿一条链接:

    /* http://meyerweb.com/eric/tools/css/reset/
    v5.0.1 | 20191019
    License: none (public domain)
    */
    
    html, body, div, span, applet, object, iframe,
    h1, h2, h3, h4, h5, h6, p, blockquote, pre,
    a, abbr, acronym, address, big, cite, code,
    del, dfn, em, img, ins, kbd, q, s, samp,
    small, strike, strong, sub, sup, tt, var,
    b, u, i, center,
    dl, dt, dd, menu, ol, ul, li,
    fieldset, form, label, legend,
    table, caption, tbody, tfoot, thead, tr, th, td,
    article, aside, canvas, details, embed,
    figure, figcaption, footer, header, hgroup,
    main, menu, nav, output, ruby, section, summary,
    time, mark, audio, video {
     margin: 0;
     padding: 0;
     border: 0;
     font-size: 100%;
     font: inherit;
     vertical-align: baseline;
    }
    /* HTML5 display-role reset for older browsers */
    article, aside, details, figcaption, figure,
    footer, header, hgroup, main, menu, nav, section {display: block;}
    /* HTML5 hidden-attribute fix for newer browsers */
    *[hidden] {display: none;}
    body {line-height: 1;}
    menu, ol, ul {list-style: none;}
    blockquote, q {quotes: none;}
    blockquote:before, blockquote:after,
    q:before, q:after {
     content: '';
     content: none;
    }
    table {
     border-collapse: collapse;
     border-spacing: 0;
    }
  2. 粘贴代码到 reset.css,放到 static 目录下,并在 nuxt.config.js 引入:

    head: {
      ...,
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'},
      {rel: 'stylesheet', type: 'text/css', href: '/reset.css'}    // 引入
    ]
     }, 

  3. 同样,你也能够放到该文件中的 css 对象里,以数组项模式存在。

五、nuxtjs 中应用 asyncData 实现 SSR

Nux t 能够在 asyncDatacreated中做 axios 申请。但在 created 中做申请,渲染进去的数据不会呈现在 html 中,导致 无奈实现 SEO优化,而应用 asyncData 做申请,则 html 会被渲染进去,从而 实现 SSR<font color=”#f00″> 不是异步 </font>
asyncData中 <font color=”#f00″> 不能获取 </font>vue 的 this,所以必须returntemplate 中可间接花括号调用,与应用 data 数据统一

// 页面中应用 asyncData 能够实现 SSR 渲染,但赋值是间接 return {data}
async asyncData() {let result = await BannerApi();
   if (result.errCode === 0) {
     let banner = result.data;
     return {banner};
   }
 },
export default {asyncData({ params,query}) {return axios.get(`https://my-api/posts/${params.id}`).then(res => {return { title: res.data.title}
    })
  }
}

六、路由

page 页面中新建 vue 组件,路由 <font color=”#f00″> 主动生成 </font> 同文件名统一的路由

6.1 动静嵌套子路由

  1. 能够通过 vue-router 的子路由创立 Nuxt.js 利用的嵌套路由。
  2. 创立内嵌子路由,你须要增加一个 Vue 文件,同时增加一个与该文件同名的目录用来寄存子视图组件。
  3. <font color=”#f00″>Warning</font>: 别忘了在父组件(.vue 文件) 内减少 <nuxt-child/> 用于显示子视图内容。

七、Nuxt 解决跨域

  1. 装置 proxy

    npm i @nuxtjs/proxy -D
  2. nuxt.config.js 中增加:

    module.exports = {
      ...,
      modules: [
     '@nuxtjs/axios',
     '@nuxtjs/proxy'
      ],
      axios: {
     proxy: true,
     prefix: '/',
     credentials: true
      },
      proxy: {
     '/api/': {
       target: 'http://127.0.0.1:9000/web', // 指标服务器 ip
       pathRewrite: {
         '^/api/': '/',
         changeOrigin: true
       }
     }
      }
    }
    
  3. axiosbaseURL 的话应用 /api 即可

八、Nuxt.js 重定向路由形式

8.1 形式 1

通过 nuxt.config.js 设置,在 nuxt.config.js 文件增加上面的配置。redirect 示意重定向的路由。

router: {extendRoutes(routes, resolve) {
      routes.push({
        path: '/',
        redirect: '/film'
      })
    }
  }

8.2 形式 2

通过中间件文件,在目录中的 middleware 增加一个名为:redirect.js 的文件

  1. redirect.js 中写入以下代码,其中 pathredirect 的路由本人定义。

    export default function ({
      isHMR,
      app,
      store,
      route,
      params,
      error,
      redirect,
    }) {if (isHMR) return; // 用来判断热更新
      // 页面均放在_lang 文件夹下,即 lang 为动静路由参数;
      /* if (!params.lang) { // 此写法会呈现路由重定向次数过多的问题;return redirect('/' + defaultLocale + '' + route.fullPath)} */
      if (route.fullPath == "/") {return redirect("/home");
      }
      if (route.fullPath == '/vue') {return redirect('/vue/basics')
      }
    }
    
  2. 最初须要在 nuxt.config.js 文件中增加

    router: {middleware: 'redirect'}

九、nuxt 中应用 vue 插件

  1. plugins 目录上面创立一个 xxx.js

    import Vue from 'vue'
    import VueHighlightJS from 'vue-highlightjs' // 通知 Vue 要应用插件 vue-highlightjs
    import 'highlight.js/styles/atom-one-dark.css'
    
    Vue.use(VueHighlightJS)

  2. nuxt.config.js 中配置:

    export default {plugins: ['~/plugins/xxx']
    }

总结

提醒:这里对文章进行总结:

例如:以上就是明天要讲的 Nuxtjs 内容,本文只是简略介绍了 Nuxtjs 的一些应用,能够让你疾速上手 Nuxt,当然 Nuxt 里边还有好多弱小的性能,大家能够去官网再具体看看。

正文完
 0