1 方法一 在 template
标签中使用 src
属性引入模板文件:
<template src="./MyComponentTemplate.html"></template>
2 方法二 在 <script>
标签中使用 require
或 import
引入模板文件:
import MyComponentTemplate from './MyComponentTemplate.html';
export default {
template: MyComponentTemplate
// ...
}
export default {
template: require('./MyComponentTemplate.html')
// ...
}
3 方法三 在 vue.config.js
中配置 vue-loader
的 transformAssetUrls
选项,使其支持在模板中使用外部文件
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
options.transformAssetUrls = {
'my-custom-element': 'src'
};
return options;
})
}
};
4 总结
以上三种方式中,
第一种方式最好的好处是让我们的单文件组件保持精简,比较易读易维护,
但是在依赖管理和构建上会增加些负担。
第二种方式中,需要打包器支持加载 HTML 文件,比如 webpack,有些打包器不支持这个功能,
需要配置一些特殊的插件,比较麻烦。
第三种方式在开发依赖管理和构建上比较方便,但是会对构建过程造成一定的性能损失。