不使用Vue CLI等构建工具时如何引入外部HTML作为Vue组件模板
可行实现方案(无需任何构建工具)
以下是两种最常用的实现方式:
方法1:单组件对应单独HTML模板文件
- 先将组件的模板代码单独存为一个HTML文件,比如命名为
my-component-template.html,文件内仅保留模板代码,无需额外标签:
<p>Hello, world !!!</p>
- 通过原生
fetch请求拿到模板文件内容后,再注册组件即可,代码示例:
fetch('./my-component-template.html') .then(response => response.text()) .then(templateContent => { const MyComponent = Vue.component('my-component', { data () { // 业务数据逻辑 }, methods: { // 业务方法逻辑 }, template: templateContent }); })
注意:本地调试时需要通过HTTP服务访问页面,不能直接用file协议打开HTML文件,否则会触发跨域限制导致请求失败。
方法2:多组件模板统一存放在单个HTML文件
如果有多个组件需要拆分模板,可以把所有模板集中放在同一个外部HTML文件里,用带唯一ID的<template>标签包裹,一次请求后所有组件都可以复用:
- 外部模板文件
templates.html示例:
<template id="my-component-tpl"> <p>Hello, world !!!</p> </template> <template id="other-component-tpl"> <div>其他组件的模板内容</div> </template>
- 业务代码实现:
fetch('./templates.html') .then(response => response.text()) .then(tplsContent => { // 将模板内容插入当前页面的隐藏容器中 const tplContainer = document.createElement('div'); tplContainer.style.display = 'none'; tplContainer.innerHTML = tplsContent; document.body.appendChild(tplContainer); // 注册组件时直接关联对应模板ID即可 Vue.component('my-component', { data() {}, template: '#my-component-tpl' }); Vue.component('other-component', { data() {}, template: '#other-component-tpl' }); })
如果使用的是Vue3,仅需要将组件注册API替换为对应app.component即可,模板加载逻辑完全一致。
内容的提问来源于stack exchange,提问作者Fred Burette
相关产品推荐
相关产品推荐

