简体   繁体   中英

Cannot pass value from main.js to index.html

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!

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/vue@3.0.11/dist/vue.esm-browser.js'; const vm = Vue.createApp({ data () { return { myName: 'su' } } }); vm.mount('#app'); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM