nuxtjs快速上手(nuxt2)

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快速上手(nuxt2)_第1张图片

二、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"
        }
    }
} 

nuxtjs快速上手(nuxt2)_第2张图片

三、在nuxt中使用less

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

    npm install less [email protected] --save-dev
  2. 全局样式文件
  3. static 目录中创建 base.less 文件,用来写全局样式。然后打开 nuxt.config.js 并找到 css

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

四、nuxtjs中项目清除默认样式

  1. 打开 reset-cssnpm 网站,随便拿一条链接:

    /* 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' }    // 引入
    ]
     }, 

    nuxtjs快速上手(nuxt2)_第3张图片

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

五、nuxtjs中使用asyncData实现SSR

Nuxt可以在asyncDatacreated中做axios请求。但在created中做请求,渲染出来的数据不会出现在html中,导致无法实现SEO优化,而使用asyncData做请求,则html会被渲染出来,从而实现SSR不是异步
asyncData不能获取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组件,路由 自动生成 同文件名一致的路由
nuxtjs快速上手(nuxt2)_第4张图片

6.1 动态嵌套子路由

  1. 可以通过 vue-router 的子路由创建 Nuxt.js 应用的嵌套路由。
  2. 创建内嵌子路由,你需要添加一个 Vue 文件,同时添加一个与该文件同名的目录用来存放子视图组件。
  3. Warning: 别忘了在父组件(.vue文件) 内增加 用于显示子视图内容。
    nuxtjs快速上手(nuxt2)_第5张图片

七、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的文件
nuxtjs快速上手(nuxt2)_第6张图片

  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'}

    nuxtjs快速上手(nuxt2)_第7张图片

九、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)

    nuxtjs快速上手(nuxt2)_第8张图片

  2. nuxt.config.js中配置:

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

    nuxtjs快速上手(nuxt2)_第9张图片

总结

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

例如:以上就是今天要讲的 Nuxtjs 内容,本文只是简单介绍了 Nuxtjs 的一些使用,可以让你快速上手 Nuxt,当然 Nuxt 里边还有好多强大的功能,大家可以去官网再详细看看。

你可能感兴趣的:(nuxtjs快速上手(nuxt2))