LoginSignup
3
2

More than 3 years have passed since last update.

Nuxt.jsのAsyncDataでaxiosや自作pluginを使う方法

Posted at

AsyncDataとは

Nuxt.jsにおけるAsyncDataは Vue || view インスタンスがつくられる前にAPIからデータをとってくるなどができる優れモノです。しかし、インスタンスがないためthisとかが使ずpluginにしている関数を呼び出す方法にすこし苦戦することがあります。

簡単です context を使いましょう。

asyncDataの引数にcontextを入れるとつかえます。console.logなどで見てもらえばわかりますが、contextからはstoreやrouteなども参照できます。

index.vue
//省略

<script>
export default {
 async asyncData (context) {
  const hoge = await context.$axios.get('hoge')
   .then((res) => {
    return res.data
   }).catch(() => { '省略' })
  return { fuga: hoge }
 }
}
<script>

//省略

自作pluginをどうやってcontextにいれるか

contextはオブジェクト形式になっているのでチェーンさせてしまえば入れられます。

plugins/hogeplugin.js
export default (context) => {
  context.$hogeplugin = () => {
    let url
    url = 'Hello world'
    return url
  }
}

このようにすれば先ほどのcontextから context.$hogeplugin のように呼び出すことができます。

nuxt.config.jsにプラグインの記述も忘れずに!

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2