+
95
-

回答

要在浏览器中直接引用 Vue 组件而不使用 Webpack 打包,你可以使用 Vue 的单文件组件(SFC)的替代方案。以下是一个简单的步骤指南:

创建一个 HTML 文件:首先,创建一个 HTML 文件,引入 Vue 库和你的组件脚本。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue Component Example</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
    <div id="app">
        <my-component></my-component>
    </div>
    <script src="my-component.js"></script>
    <script>
        new Vue({
            el: '#app'
        });
    </script>
</body>
</html>

创建一个 JavaScript 文件:创建一个 JavaScript 文件(例如 my-component.js),在其中定义你的 Vue 组件。

Vue.component('my-component', {
    template: `
        <div>
            <h1>Hello, Vue!</h1>
            <p>This is a Vue component.</p>
        </div>
    `
});

在浏览器中打开 HTML 文件:现在,你可以直接在浏览器中打开这个 HTML 文件,看到你的 Vue 组件正常工作。

使用单文件组件的替代方案

如果你希望使用类似单文件组件的结构,可以使用 vue.global.js,它允许你在浏览器中直接编写和使用 Vue 组件。

引入 vue.global.js:修改 HTML 文件,引入 vue.global.js。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue Component Example</title>
    <script src="https://unpkg.com/vue@next/dist/vue.global.js"></script>
</head>
<body>
    <div id="app">
        <my-component></my-component>
    </div>
    <script type="module" src="my-component.js"></script>
    <script type="module">
        import { createApp } from 'https://unpkg.com/vue@next/dist/vue.esm-browser.js';
        import MyComponent from './my-component.js';

        const app = createApp({});
        app.component('my-component', MyComponent);
        app.mount('#app');
    </script>
</body>
</html>

定义组件:修改 my-component.js,使用 ES 模块格式。

export default {
    template: `
        <div>
            <h1>Hello, Vue!</h1>
            <p>This is a Vue component.</p>
        </div>
    `
};

通过这种方式,你可以在浏览器中直接使用 Vue 组件,而不需要 Webpack 或其他构建工具。

网友回复

我知道答案,我要回答