首页 > 解决方案 > 如何在基本的 Vue html 文件中使用 Vue 组件 (.udm.js)?

问题描述

我构建了一个Vue component"build-bundle": "vue-cli-service build --target lib --name my-component ./src/myComponent.vue". 在dist我的文件夹中:

现在,为了GitHub Page发布,我正在构建一个页面来解释组件的细节和特性。我将使用一个/docs文件夹作为根目录GitHub Page(我不想使用gh-pages分支)。

为此,我必须构建一个基本的Vue应用程序,而不需要Vue CLIWebpack或者这样。

index.html看起来像这样:

<!DOCTYPE html>
<html lang="en">
  <head>
  ...
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <script src="js/my-component.umd.js"></script> 
  ...
  </head>

  <body>
    ...
    <div id="app">..</div>
    ...
    <script type="module">
      var app = new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue!'
        },
        components: {
          myComponent: my-component   
        }
      })
    </script>
  </body>
</html>

信息:我复制dist/my-component.umd.js到该docs/js文件夹​​以便拥有一个独立的文件夹。

如果我不使用 Vue 脚本中的组件(Vue 工作正常),页面运行良好。但是,当我使用该组件时,页面会显示此错误,该错误(index):199 Uncaught ReferenceError: vue is not defined直接指向myComponent: my-component.

有什么想法或建议吗?

标签: javascriptvue.jsvuejs2vue-componentgithub-pages

解决方案


尝试将脚本放在应用代码之前的正文部分。否则,运行您的应用程序代码后可能会加载 Vue 库

<!DOCTYPE html>
<html lang="en">
  <head>
  ...
  ...
  </head>

  <body>
    ...
    <div id="app">..</div>
    ...
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="js/my-component.umd.js"></script> 
    <script type="module">
      var app = new Vue({
        el: '#app',
        data: {
          message: 'Hello Vue!'
        },
        components: {
          myComponent: my-component   
        }
      })
    </script>
  </body>
</html>

推荐阅读