vue-youtube / docs

Documentation for VueYoutube
https://vue-youtube.github.io/docs/
MIT License
6 stars 0 forks source link

Dynamic loading of vue-youtube #4

Closed nathanchase closed 1 year ago

nathanchase commented 1 year ago

I'd like to do a dynamic load of vue-youtube, rather than a plugin that adds to my Nuxt 3 entry bundle.

Something like this:

// components/YourComponent.vue
<template>
  <div v-if="youtubeReady">
    <!-- Your component's template -->
    <YoutubeIframe video-id="your-video-id" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

const nuxtApp = useNuxtApp(); // access the Nuxt app context

let youtubeManager; // Define a variable to hold the YouTube manager

const loadYoutube = async () => {
  const { createManager } = await import('@vue-youtube/core');
  const { YoutubeIframe } = await import('@vue-youtube/component');

  youtubeManager = createManager(); // Initialize the YouTube manager
  nuxtApp.vueApp.use(manager); // <- this is where I think the issue lies
};

export default {
  setup() {
    const youtubeReady = ref(false);

    onMounted(() => {
      // Load the YouTube package when the component is mounted
      loadYoutube().then(() => {
        youtubeReady.value = true;
      });
    });

    return {
      youtubeReady,
    };
  },
};
</script>

The problem is, by doing it this way, Vue complains with an error of App already provides property with key "vue-youtube". It will be overwritten with the new value.

Is there some way to dynamically use vue-youtube rather than having to provide it to vueApp?

suterma commented 1 year ago

You have two options:

Techassi commented 1 year ago

Regarding Nuxt support: This is indeed very tricky. There seems to be an issue with the provide/inject API. I'm still working on adding official support via a Nuxt module.

To dynamically load the required scripts, it is indeed recommended to use deferLoading as @suterma mentioned. Let me know if you need any further support!

nathanchase commented 1 year ago

Perfect. Thank you @suterma @Techassi.