0

Here is the vue object I create in main.js with a value : myName

import Vue from "vue";

const vm = Vue.createApp({
    data () {
        return {
            myName: 'su'
        }
    }
});

vm.mount('#app');

and I'd like to show 'su' in index.html

here is html code

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
  </head>
  <body>
    123
    <div id="app">
      name : {{ myName }}
    </div>
    
    <script type="module" src="/src/main.js">

    </script>
  </body>
</html>

and it does't work and show

name : {{ myName }}

Can anyone help pls thanks!

2
  • Next time, please at least consult your browser's developer tools console for errors before asking on StackOverflow. The console would have clearly showed you Vue is undefined.
    – connexo
    Apr 11, 2021 at 12:38
  • Is your question answered? If yes, please mark the answer correct. If not, please comment accordingly.
    – connexo
    Apr 12, 2021 at 11:08

1 Answer 1

1

The reason it doesn't work is because you're never actually importing Vue. Checking your browser console would have shown you that Vue is undefined.

import Vue from "vue";

needs a build tool like webpack and will resolve the import against your node_modules folder.

Since you are directly importing Vue in a module right in your page, you need to import from a path available to the browser:

123
<div id="app">
  name : {{ myName }}
</div>

<script type="module">
  import * as Vue from 'https://unpkg.com/[email protected]/dist/vue.esm-browser.js'; 
  const vm = Vue.createApp({ 
    data () { 
      return { 
        myName: 'su' 
      } 
    } 
  }); 
  vm.mount('#app');
</script>

10
  • my question is how to pass the value from main.js, the first code is my main.js and my browser didn't show any error
    – 蘇柏綸
    Apr 11, 2021 at 13:31
  • I already tried your way and it works but that is not what I am trying to fix
    – 蘇柏綸
    Apr 11, 2021 at 13:32
  • That is the only reason Vue is not processing your {{ myName }}. Vue is not active at all.
    – connexo
    Apr 11, 2021 at 13:33
  • so is it possible that i create vm in my main.js and pass the value to index.html?
    – 蘇柏綸
    Apr 11, 2021 at 13:34
  • Sure, that is the most basic stuff in Vue. It's just Vue doesn't work if Vue is never loaded :)
    – connexo
    Apr 11, 2021 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.