Search code examples
javascriptvue.jsvuejs2cdn

How to import Vue components from browser - via CDN


I'm trying to import a Vue.js component (@chenfengyuan/vue-qrcode) using UNPKG as CDN.

Currently, my setup works like this:

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
<script src="https://unpkg.com/@chenfengyuan/vue-qrcode@1.0.1/dist/vue-qrcode.min.js"></script>
<script>Vue.component(VueQrcode.name, VueQrcode);</script>

<script type="module" src="/client.js"></script>


In my client.js file I have my Vue instance:

new Vue({
  el: "#app",
  data: {
    msg: "Vue js Hello World - Your First Vue.js App"
  }
});

The setup that I would like to achieve is something like this:

<script type="module" src="/client.js"></script>

Then my client.js would look something like this:

import Vue from 'https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.esm.browser.js'

import VueQrcode from 'https://unpkg.com/@chenfengyuan/vue-qrcode@1.0.1/dist/vue-qrcode.min.js'

Vue.component(VueQrcode.name, VueQrcode);
new Vue({
  el: "#app",
  data: {
    msg: "Vue js Hello World - Your First Vue.js App"
  }
});

The Vue template (incrustated in HTML) is the following:

<div id="app">
      <h1>{{ msg }}</h1>
      <qrcode value="https://queue-r.glitch.me" :options="{ width: 200 }"></qrcode>
</div>


But sadly, this approach does not work. All I see in the console is that the custom tag is not recognized. With this approach, I want to achieve full separation of my Vue code from the HTML.

Any hints why it's not working as I want? What do you think?


Solution

  • The example you posted works fine, here is a working example.

    new Vue({
      el: "#app",
      data: {
        msg: "Vue js Hello World - Your First Vue.js App"
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://unpkg.com/@chenfengyuan/vue-qrcode@1.0.1/dist/vue-qrcode.min.js"></script>
    <script>Vue.component(VueQrcode.name, VueQrcode);</script>
    
    <div id="app">
          <h1>{{ msg }}</h1>
          <qrcode value="https://queue-r.glitch.me" :options="{ width: 200 }"></qrcode>
    </div>