0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxtでコンポーネントのファイルパスを動的な文字列で読み込みたいぜ・・・

Posted at

Nuxtでコンポーネントファイルを動的に読み込みたい場合の道2選。

さて、画面の条件によって読み込みたいコンポーネントを変えたい、差し替えたいって時ってありますよね。

動的コンポーネントのファイルパスが事前にわかる場合

<template lang="pug">
section
  component(:is='loadComponent') 
</template>
<script>
import customComponent1 from '~/components/customComponent1.vue'
import customComponent2 from '~/components/customComponent2.vue'
export default {
  components: {
    customComponent1,
    customComponent2
  },
  data() {
    return {
      // 後は条件で適当に変えて
      loadComponent: customComponent1,
    }
  }
}
</script>

これで、お好みのトリガーでloadComponentの値を事前に読み込んでおいたcomponentsのどれかに差し替えれば簡単にコンポーネントの動的切り替えができる。簡単ですね。

動的コンポーネントのファイルパスが事前にわからない場合

import customComponent1 from '~/components/customComponent1.vue'のファイルパスをstoreの値やapiから取得した値など、動的に変えたいときは、以下のようにしてください。

<template lang="pug">
section
  component(v-if='customComponent', :is='customComponent') 
</template>
<script>
export default {
  data() {
    return {
      customComponent: null,
    }
  },
  computed: {
    listCustomComponent() {
      return '動的に読み込みたいコンポーネントのファイル名'
    },
  },
  mounted() {
    if (this.listCustomComponent) {
      this.customComponent = () =>
        import(`~/components/xxxx/${this.listCustomComponent}`)
    }
  },
}
</script>

これでcomponentの指定を動的な文字列で指定することができます。
当たり前ですがファイルパスが間違っていると読み込まれませんので要注意。

この記事が役に立ったと思ったら!LGTMボタン!お願いしゃっす!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?