How to include Vue.js in HTML Document Through CDN?

There are two ways to install Vue.js, one is installed through npm commands, and the second is through CDN. Installing Vue.js through CDN is simple and easy. Build step and SFC (Single File Components) available in the node environment. So if you install Vue.js through CDN, it won’t be available.

Note: Vue Single File Component (*.vue files, abbreviated as SFC) is a special file format that enables developers to use the template, logic, and styling of a Vue component in a single file.

Setup Vue.js Application Through CDN

Below is the CDN for Vue.js, copy and paste it into the head section of the HTML document. It loads the global build of Vue which means your HTML document will be able to access all top level features.

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

Next, add below code that simply shows “Hello Vue!” message in the div.

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">{{ message }}</div>

<script>
  const { createApp } = Vue
  createApp({
    data() {
      return {
        message: 'Hello Vue!'
      }
    }
  }).mount('#app')
</script>

In the above script, the first line includes Vue.js to HTML document through CDN. In the second line, a div has an ID attribute whose value is app. Also it has a message variable with curly braces which data comes from data() method.

Next, we have createApp constant that creates a Vue instance. Vue instance createApp is mounted with div element that has #app id.  After creating a Vue instance, we can use Vue’s data() method that returns variables of the app.

The data() method returns a message variable with static string. As you can see we have same message variable in the div element which value comes from data() method because createApp is mounted with div element through the id attribute.

Conclusion

In this article, we learned how to include Vue.js through CDN and create Vue.js application. If you would like to learn more, check out our Vue.js page.