Nuxt.js基礎(chǔ)

一、Nuxt.js是什么

  • 一個基于Vue.js生態(tài)的第三方開源服務(wù)端渲染應(yīng)用框架
  • 他可以幫助我們輕松的使用vue.js技術(shù)棧構(gòu)建同構(gòu)應(yīng)用
  • 中文文檔
  • GitHub倉庫

二、Nuxt.js的使用方式

  • 初始項(xiàng)目
  • 已有的Node.js服務(wù)端項(xiàng)目
    • 直接吧Nuxt當(dāng)做一個中間件集成到Node Web Server 中
  • 現(xiàn)有的Vue.js項(xiàng)目
    • 非常熟悉Nuxt.js
    • 至少百分之十的代碼改動

三、從頭開始新建項(xiàng)目

 mkdir <項(xiàng)目名>     // 創(chuàng)建文件夾
 cd <項(xiàng)目名> // 進(jìn)入文件目錄
npm init -y  // 初始化package.json文件
npm install --save nuxt   // 安裝nuxt包

// 修改package.json 文件,創(chuàng)建命令
// 下面的配置使得我們可以通過運(yùn)行 npm run dev 來運(yùn)行 nuxt。
{
  "name": "my-app",
  "scripts": {
    "dev": "nuxt"
  }
}
  • 創(chuàng)建第一個頁面 pages/index.vue
<template>
  <h1>Hello world!</h1>
</template>
  • 運(yùn)行
npm run dev
// 現(xiàn)在我們的應(yīng)用運(yùn)行在 http://localhost:3000 上運(yùn)行

四、NuxtJS案例代碼分支說明

git init  // 初始化本地倉庫
  • 創(chuàng)建 .gitignore 文件 把不需要git管理的資源文件排除
node_modules
.nuxt
  • 查看
git status
  • 添加所有文件至?xí)捍鎱^(qū)
git add .
  • 提交
git commit -m '初始化Nuxt.js項(xiàng)目'
  • 創(chuàng)建分支
git branch 02-router
  • 查看分支
git branch
  • 切換分支
git checkout 02-router

五、Nuxt.js 基礎(chǔ)路由

假設(shè) pages 的目錄結(jié)構(gòu)如下:

pages/
--| user/
-----| index.vue
-----| one.vue
--| index.vue

那么,Nuxt.js 自動生成的路由配置如下:

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'user',
      path: '/user',
      component: 'pages/user/index.vue'
    },
    {
      name: 'user-one',
      path: '/user/one',
      component: 'pages/user/one.vue'
    }
  ]
}

六、路由-路由導(dǎo)航

  • 切換并且新建分支
git checkout -b 03-路由導(dǎo)航
<template>
  <nuxt-link to="/">首頁</nuxt-link>
</template>
methods:{
        onClick(){
            this.$router.push('/')
        }
    }

七、路由-動態(tài)路由

pages/
--| _slug/
-----| comments.vue
-----| index.vue
--| users/
-----| _id.vue
--| index.vue

Nuxt.js 生成對應(yīng)的路由配置表為:

router: {
  routes: [
    {
      name: 'index',
      path: '/',
      component: 'pages/index.vue'
    },
    {
      name: 'users-id',
      path: '/users/:id?',
      component: 'pages/users/_id.vue'
    },
    {
      name: 'slug',
      path: '/:slug',
      component: 'pages/_slug/index.vue'
    },
    {
      name: 'slug-comments',
      path: '/:slug/comments',
      component: 'pages/_slug/comments.vue'
    }
  ]
}

你會發(fā)現(xiàn)名稱為 users-id 的路由路徑帶有 :id? 參數(shù),表示該路由是可選的。如果你想將它設(shè)置為必選的路由,需要在 users/_id 目錄內(nèi)創(chuàng)建一個 index.vue 文件。

  • 路由參數(shù)校驗(yàn)
export default {
  validate({ params }) {
    // 必須是number類型
    return /^\d+$/.test(params.id)
  }
}

如果校驗(yàn)方法返回的值不為 true或Promise中 resolve 解析為false或拋出 Error , Nuxt.js 將自動加載顯示 404 錯誤頁面或 500 錯誤頁面。
想了解關(guān)于路由參數(shù)校驗(yàn)的信息,請參考 頁面校驗(yàn) API

八、路由-嵌套路由

  • Vue Router嵌套路由

  • Nuxt.js嵌套路由
    你可以通過 vue-router 的子路由創(chuàng)建 Nuxt.js 應(yīng)用的嵌套路由。

  • 創(chuàng)建內(nèi)嵌子路由,你需要添加一個 Vue 文件,同時添加一個與該文件同名的目錄用來存放子視圖組件。
    別忘了在父組件(.vue文件) 內(nèi)增加 <nuxt-child/> 用于顯示子視圖內(nèi)容。

假設(shè)文件結(jié)構(gòu)如:

pages/
--| users/
-----| _id.vue
-----| index.vue
--| users.vue

Nuxt.js 自動生成的路由配置如下:

router: {
  routes: [
    {
      path: '/users',
      component: 'pages/users.vue',
      children: [
        {
          path: '',
          component: 'pages/users/index.vue',
          name: 'users'
        },
        {
          path: ':id',
          component: 'pages/users/_id.vue',
          name: 'users-id'
        }
      ]
    }
  ]
}

九、路由-路由配置

/**
 * Nuxt 路由配置
 * base 自定義根目錄名稱  整個單頁面應(yīng)用的所有資源可以通過 /demo/ 來訪問
 */
module.exports = {
  router: {
    base: '/demo/',
    // routes  :  一個數(shù)組  路由配置表
    // resolve  :  解析路由組建路徑
    extendRoutes(routes, resolve) {
      routes.push({
        path: '/hello',
        name: 'hello',
        component: resolve(__dirname, 'pages/about.vue'),
      })
    },
  },
}

十、視圖-模板

image.png

十一、視圖-布局

  • 自定義布局
    layouts 目錄中的每個文件 (頂級) 都將創(chuàng)建一個可通過頁面組件中的 layout 屬性訪問的自定義布局。

假設(shè)我們要創(chuàng)建一個并將其保存到layouts/blog.vue:

<template>
  <div>
    <div>我的博客導(dǎo)航欄在這里</div>
    <nuxt />
  </div>
</template>

然后我們必須告訴頁面 (即pages/posts.vue) 使用您的自定義布局:

<template>
  <!-- Your template -->
</template>
<script>
  export default {
    layout: 'blog'
    // 當(dāng)前默認(rèn)父組件為blog
  }
</script>

十二、異步數(shù)據(jù) - asyncData

  • 文檔
  • 基本用法
    • 它會將asyncData 返回的數(shù)據(jù)融合組件data方法返回?cái)?shù)據(jù)一并給組件
    • 調(diào)用時機(jī):服務(wù)端渲染期間和客戶端路由更新之前
  • 注意事項(xiàng)
    • 只能在頁面組件中使用,子組件中不能使用
    • 沒有this,因?yàn)樗窃诮M件初始化之前被調(diào)用的
<template>
  <div>
    <h1>頁面</h1>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "homePage",
  /**
   * 當(dāng)你想要動態(tài)頁面內(nèi)容有利于SEO
   * 或者是提升首屏渲染速度的時候
   * 就在asyncData中發(fā)請求拿數(shù)據(jù)
   *
   * 拿到的數(shù)據(jù)最終會合并到data中
   */

  async asyncData() {
    const res = await axios({
      method: "GET",
      url: "http://localhost:3000/data.json",
    });
    return res.data;
  },
  /***
   * 如果是非異步數(shù)據(jù)或者普通數(shù)據(jù)
   * 則正常初始化到data中即可
   */
  data(){
    return{
      foo:'bar'
    }
  }
};
</script>

<style>
</style>

十三、異步數(shù)據(jù) - 上下文對象

<template>
  <div>
    <h1>{{ article.title }}</h1>
    <div>{{ article.body }}</div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "articalPage",
  async asyncData(context) {
    const { data } = await axios({
      method: "GET",
      url: "http://localhost:3000/data.json",
    });

    // context.params.id  參數(shù)
    const id = Number.parseInt(context.params.id);
    return {
      article: data.posts.find((item) => item.id === id),
    };
  },
};
</script>

<style>
</style>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容