如何在静态页面挂载Vue组件?

问题描述 投票:0回答:1

如何在现有的 HTML 页面中挂载 Vue 组件? 我尝试了几个小时,我最近的尝试如下:

main.js:

import Vue from 'vue'
Vue.component('MyComponent', require('./MyComponent.vue'));

我的组件.vue:

<template>
   <H2>Hi</H2>
</template>
<script setup>
    console.log('setup')
</script>
<script>
    import { ref } from 'vue'
    import { Chat } from '@chat-ui/vue3'
    export default {
        name: 'MyComponent',
        data() {
        },
        mounted() {
        }
    }
</script>

在 HTML 中我添加了一个

<MyComponent></MyComponent>
元素。

当我想通过Vite构建它时,出现以下错误: “default”不是由“node_modules/vue/dist/vue.runtime.esm-bundler.js”导出,而是由“src/main.js”导入。

非常感谢任何帮助。

vue.js vuejs3 vue-component
1个回答
0
投票

您遇到的错误消息表明您在

main.js
文件中导入 Vue 的方式存在问题。该错误表明 Vue 正在尝试从
vue.runtime.esm-bundler.js
导入“默认”导出,但无法找到它。

要解决此问题,您应该调整导入 Vue 的方式。这是您的

main.js
文件的更正版本:

import { createApp } from 'vue'; // Import createApp instead of importing Vue directly
import App from './App.vue';

const app = createApp(App);
app.mount('#app');

在上面的代码中,我们使用

createApp
创建一个Vue应用程序实例,然后将其挂载到ID为
#app
的元素上。这是创建 Vue 3 应用程序的标准方法。

接下来,让我们确保在 Vue 组件中正确导入和使用

MyComponent.vue
。在您的 HTML 文件中,您想要使用
MyComponent
的位置,请确保您也正确导入它:

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- ... -->
</head>
<body>
    <div id="app">
        <MyComponent></MyComponent> <!-- Make sure this element is inside the #app div -->
    </div>

    <script type="module" src="/path-to-your-main.js"></script>
</body>
</html>

确保具有

id
app
的元素包围您的
MyComponent
元素。另外,请确保将
/path-to-your-main.js
替换为
main.js
文件的实际路径。

通过这些更改,您的 Vue 组件应该正确安装在 HTML 页面中。如果您仍然遇到问题,请仔细检查您的项目结构并确保正确安装了必要的依赖项。

© www.soinside.com 2019 - 2024. All rights reserved.