引入CDN版Vue的单index.html如何直接加载外部.vue单文件组件?
Vue CDN模式动态加载.vue单文件组件方案
核心结论
纯客户端单个index.html可实现该需求,无需自行手动拆分解析SFC的各个逻辑块。
轻量无额外依赖方案
该方案适用于使用Options API编写的.vue组件,无需引入第三方库,仅优化原有解析逻辑即可支持methods、生命周期钩子、computed等所有组件配置项:
<head> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="_app"> <component-form></component-form> </div> <script> ;(async function(){ // 拉取.vue文件内容 const form = await fetch(`lite/vuejs/cash-sale.vue`).then(res => res.text()) // 用正则匹配script和template内容,支持标签带属性的场景 const script = form.match(/<script[^>]*>([\s\S]*?)<\/script>/)?.[1] || '' const template = form.match(/<template[^>]*>([\s\S]*?)<\/template>/)?.[1] || '' // 直接执行script内容得到完整组件配置对象,无需手动解析各个字段 const componentOptions = new Function(`return ${script.replace('export default ', '').trim()}`)() // 注入模板 componentOptions.template = template const app = Vue.createApp({}) app.component(`component-form`, componentOptions) app.mount(`#_app`) })(); </script> </body>
方案说明
- 正则匹配比硬编码索引截取更稳定,可兼容带属性的标签场景
- 通过
new Function执行script内容,直接拿到完整的组件配置对象,所有methods、mounted、watch等配置都会自动保留,无需手动拆分解析
全SFC特性支持方案
如果需要支持<script setup>、style scoped、JSX等所有.vue单文件特性,可引入浏览器端SFC编译工具,无需自行处理任何解析逻辑,仅需调用加载接口即可拿到可直接注册的组件对象。
内容的提问来源于stack exchange,提问作者zummon
相关产品推荐
相关产品推荐

