Node.js/nuxt/axios:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 引言 == <blockquote><pre> @nuxtjs/axios</pre></blockquote> nuxt 自带 @nuxtjs/axios,不需单独安装 axios。 在页面组件中引用时,在 mounted…”
 
Kangkk​(留言 | 贡献)
第19行: 第19行:
     }
     }
</script></syntaxhighlight>
</script></syntaxhighlight>
需要注意的是 @nuxtjs/axios 不支持 axios.all 方法。(使用 Promise.all 代替)
<syntaxhighlight lang="javascript">
// In asyncData or fetch
// Parallel requests
const [ foo, bar] = await Promise.all([getFoo(), getBar()])
// Sequential requests
const foo= await getFoo()
const bar= await getBar()</syntaxhighlight>
<syntaxhighlight lang="javascript">
Promise.all([
      $axios.get('/v2/home/menus'),
      ...
    ]).then(([ menuRes,...]) => {
      return {
        navMenus: menuRes.data.list,
        ...
      }
    })</syntaxhighlight>
或者自己封装
<syntaxhighlight lang="javascript">
// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};
// Axios.speard
module.exports = function spread(callback) {
  return function wrap(arr) {
    return callback.apply(null, arr);
  }
};</syntaxhighlight>

2020年7月26日 (日) 14:45的版本

引言

@nuxtjs/axios

nuxt 自带 @nuxtjs/axios,不需单独安装 axios。

在页面组件中引用时,在 mounted 中有效,在 methods 中无效。

<script>
    export default {
        name: "ly-footer",
...
        mounted() {
            this.$axios.get.....;
        },
        methods: {
...
        },
    }
</script>

需要注意的是 @nuxtjs/axios 不支持 axios.all 方法。(使用 Promise.all 代替)

// In asyncData or fetch

// Parallel requests
const [ foo, bar] = await Promise.all([getFoo(), getBar()])

// Sequential requests
const foo= await getFoo()
const bar= await getBar()
Promise.all([
      $axios.get('/v2/home/menus'),
      ...
    ]).then(([ menuRes,...]) => {
      return {
        navMenus: menuRes.data.list,
        ...
      }
    })

或者自己封装

// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};

// Axios.speard
module.exports = function spread(callback) {
  return function wrap(arr) {
    return callback.apply(null, arr);
  }
};