提出问题
.vue 文件,是 Vue 用于 组件化 开发的 文件格式。包含了 HTML代码、CSS样式和JavaScript逻辑,将它们组合在一起形成一个 独立的组件。
问题
不能在 HTML 文件中直接使用 .vue 文件,因为浏览器只能识别 .html 、.css、.js 等文件格式,无法识别 .vue 文件格式
解决
使用 http-vue-loader.js,就可以在 HTML 文件中直接引入 .vue 文件,不需要 node.js 环境,也不需要 webpack 等编译工具
介绍
http-vue-loader 是一个 Vue加载器,允许浏览器中直接 加载 和 解析 .vue 单文件组件。
官方网址:
https://github.com/FranckFreiburger/http-vue-loader
新版本(支持vue3):
https://github.com/FranckFreiburger/vue3-sfc-loader
原理
通过解析Vue组件的模板、脚本和样式,并将其转换为一个可以在浏览器中运行的JavaScript模块。
应用场景
- 在开发过程中,我们可以使用http-vue-loader来直接加载和预览Vue组件,无需进行构建和打包。
- http-vue-loader可以帮助我们更好地组织和管理Vue组件,提高项目的可维护性。
- 在需要动态加载Vue组件的情况下,http-vue-loader可以方便地实现组件的按需加载。
使用
引入js
<script src="https://unpkg.com/http-vue-loader"></script>
加载 .Vue组件 方式一
用 httpVueLoader() 加载
Vue.component('my-component', httpVueLoader('MyComponent.vue'));
加载 .Vue组件 方式二
使用 httpVueLoader.register()
httpVueLoader.register(Vue, 'my-component.vue');
new Vue({
components: [
'my-component'
]
},
加载 .Vue组件 方式三
用作插件httpVueLoader
全局组件
Vue.use(httpVueLoader);
Vue.component('my-component', 'url:my-component.vue');
局部组件
Vue.use(httpVueLoader);
new Vue({
components: {
'my-component': 'url:my-component.vue'
},
使用数组
new Vue({
components: [
'url:my-component.vue'
]
},
例子
.vue 文件
创建 my-component.vue 组件文件,内容如下:
<template>
<div class="hello">Hello {{who}}</div>
</template>
<script>
module.exports = {
data: function() {
return {
who: 'world'
}
}
}
</script>
<style>
.hello {
background-color: #ffe;
}
</style>
html 文件
创建 index.html 文件,内容如下:
<!doctype html>
<html lang="en">
<head>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/http-vue-loader"></script>
</head>
<body>
<div id="my-app">
<my-component></my-component>
</div>
<script type="text/javascript">
new Vue({
el: '#my-app',
components: {
'my-component': httpVueLoader('my-component.vue')
}
});
</script>
</body>
</html>
参考:
https://blog.csdn.net/weixin_42554191/article/details/137212852