html 不使用脚手架 如何使用vue组件 1

html 不使用脚手架 要使用vue组件的话有两种方法

1 使用 vue3-sfc-loader
git地址: https://github.com/FranckFreiburger/vue3-sfc-loader
cdn地址: https://cdn.jsdelivr.net/npm/vue3-sfc-loader

2 封装自己的ui库

这篇文章介绍第一种方法,下一篇介绍使用,封装自己的ui库
  • 首先引入vue 和 vue3-sfc-loader
  • options 是配置文件,一般使用按这个配置就足够了
  • 使用defineAsyncComponent加载vue文件,因为涉及文件读取和动态编译,所以是异步的方法
  • 组件定义 以及使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/vue@next"></script>
    <script src="./cdn.jsdelivr.net_npm_vue3-sfc-loader.js"></script>
    <title>单页面使用Vue</title>
</head>
<body>
<div id="app">
    <rjc-index></rjc-index>
</div>
<script>
    const options = {
        moduleCache: {
            vue: Vue,
        },
        getFile(url) {
            return fetch(url).then(response => response.ok ? response.text() : Promise.reject(response));
        },
        addStyle(styleStr) {
            const style = document.createElement('style');
            style.textContent = styleStr;
            const ref = document.head.getElementsByTagName('style')[0] || null;
            document.head.insertBefore(style, ref);
        },
        log(type, ...args) {
            console.log(type, ...args);
        }
    }

    const {createApp, ref, defineComponent, defineAsyncComponent} = Vue;
    //别忘记加载函数了
    const {loadModule, version} = window["vue3-sfc-loader"];
    const dynamicComponent = defineAsyncComponent(() => loadModule('./index.vue', options));

    const app = createApp({
        components: {
            rjc-index: dynamicComponent
        },
        setup() {
            return {
            };
        }
    });
    app.mount("#app");
</script>
</body>
</html>
posted @ 2023-10-21 14:16  探索星空  阅读(105)  评论(0编辑  收藏  举报