【问题标题】:Add functions to nuxt.config.js向 nuxt.config.js 添加函数
【发布时间】:2019-02-10 23:36:03
【问题描述】:

基本上我有一个应用程序,在生成时,我目前生成所有页面、站点地图和 RSS 提要,尽管我必须进行相同的 axios 调用 3 次

像这样

nuxt.config.js

generate: {
    routes: function() {
        return axios.get(data)
            .then(res => {
            ... 
            })
    }
},
sitemap: {
    routes: function() {
        return axios.get(data)
            .then(res => {
            ... 
            })
    }
},
feed: {
   etc...
}

现在有没有一种方法可以调用数据一次并将其提供给这些模块方法中的每一个?我尝试将一些函数放在 nuxt.config.js 的顶部,但在生成时出现错误

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js


    【解决方案1】:

    您可以尝试将承诺保存到变量中以供重复使用,例如

    const routesPromise = axios.get(data).then(({ data }) => data)
    
    // snip
    
    generate: {
      routes () {
        return routesPromise.then(data => {
          // ...
        })
    },
    sitemap: {
      routes () {
        return routesPromise.then(data => {
          // ...
        })
      }
    },
    // etc
    

    向 Promise 添加 .then() 调用不会修改原始解析值,因此您可以根据需要继续使用它多次,同时只发出一个 HTTP 请求。

    【讨论】:

      猜你喜欢
      • 2013-05-25
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2017-08-26
      • 2017-02-11
      • 2019-09-23
      相关资源
      最近更新 更多