编写异步 Nuxt 模块

若需在模块中使用 Promise 对象(例如通过 HTTP 客户端从远程 API 获取异步数据),Nuxt 能完美支持此需求。以下是编写异步模块时可选的实现方式:

使用 async/await

您可以在模块中使用 ES6async/await 语法配合 Axios(自第 4 章《添加视图、路由和过渡效果》以来我们一直在使用的 HTTP 客户端),如下例所示:

// modules/async-await/module.js
import axios from 'axios'

export default async function () {
  let { data } = await axios.get(
    'https://jsonplaceholder.typicode.com/posts')
  let routes = data.map(post => '/posts/' + post.id)
  console.log(routes)
}
// nuxt.config.js
modules: [
  ['~/modules/async-await/module']
]

上述示例中,我们使用 Axiosget 方法从远程 API JSONPlaceholder (https://jsonplaceholder.typicode.com/) 获取所有文章数据。首次启动 Nuxt 应用时,您将在终端看到如下输出:

[
  '/posts/1',
  '/posts/2',
  '/posts/3',
  ...
]

返回 Promise

您可以在模块中使用 Promise 链并返回 Promise 对象,如下例所示:

// modules/promise-sample/module.js
import axios from 'axios'

export default function () {
  return axios.get('https://jsonplaceholder.typicode.com/comments')
    .then(res => res.data.map(comment => '/comments/' + comment.id))
    .then(routes => {
      console.log(routes)
    })
}
// nuxt.config.js
modules: [
  ['~/modules/promise-sample/module']
]

此示例中,我们使用 Axiosget 方法从远程 API 获取所有评论数据,然后通过 then 方法链式调用 Promise 并打印结果。首次启动 Nuxt 应用时,终端将输出如下内容:

[
  '/comments/1',
  '/comments/2',
  '/comments/3',
  ...
]

这两个示例可在 GitHub 仓库的 /chapter-6/nuxtuniversal/modules/async/ 目录找到。

通过这两种异步处理方案以及您在前几节中学到的基础模块编写技能,现在您已能够轻松创建 Nuxt 模块。在接下来的章节中,我们将通过编写小型模块代码片段来展示更多实际案例。