Search code examples
vue.jsvuejs2vuejs3vue-component

vuejs app isn't running when using cdn: version 3


On my current laptop I don't have vuejs configuration hence I used cdn link yet the code isn't running

<html>
<head>
</head>
<body>

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

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

<script>

  createApp({


      let message = "hello !"
  
    }
  }).mount('#app')
</script>

</body>
</html>

what am I missing ?

by the way, as checked on this site: https://vuejs.org/guide/quick-start#using-vue-from-cdn

I should have used "setup" & "ref" but that's not what I was using..(I had a little experience with cdn before), I believe there is another way


Solution

  • In Vue 3, there are a few differences compared to Vue 2, and the code you've written reflects a Vue 2 style. Specifically, you're using createApp but trying to declare the message variable directly within it, which won't work as Vue 3 requires a different approach to handle data.

    Here's how you can correct your code to work with Vue 3 using the CDN:

    Updated Code:

    <html>
    <head>
    </head>
    <body>
    
    <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 !"
          };
        }
      }).mount('#app');
    </script>
    
    </body>
    </html>
    

    Key Changes:

    1. data function: In Vue 3, you need to define a data function that returns an object containing the reactive data.
    2. Access to createApp: Since you're using the global Vue instance from theCDN, you need to destructure createApp from Vue. This should resolve your issue and run the Vue 3 app properly using the CDN link.