如何在html(非单页vue项目)中直接引入vue文件组件

最近需要把一个自己封装好的 vue 日历组件引入到一个比较早的 vue 项目里,打开后发现这个项目是 非单页 的,即在 html 中引入 vuelib 文件, 每个 html 文件对应的 js 文件都有一个独立的 Vue实例 。在网上找到了一种方法,使用 jqueryload 方法和 vueextend 方法 ,稍微有点麻烦,最后把样式也提取到 html 的整体了才加载出来。后来又搜到一个插件 http-vue-loader,发现用起来挺方便,所以记录下

下面为插件使用的简单demo:


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>

注意: vue 文件里使用的是 module.exports


index.html
使用 httpVueLoader 加载 vue 文件,并将其注册到 vue 的 component  


<!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>

另外,这个插件还支持 sass ,更多具体用法可以查看作者的 github 地址
http-vue-loader


插件是如何实现的,有兴趣的话可以再研究下源码

1. 通过http请求加载文件
2. 将vue文件放在文档片段的容器对象,内存中
3. 处理vue文件的每一部分(template 页面文件,script js文件 和style样式 )
4. httpVueLoader('my-component.vue') 返回一个promise,成为异步组件
5. vue编译这个组件,并将其缓存

tips: 作者又开发了一个插件也支持加载 vue 文件哦,同时支持 vue2vue3 ,大家有兴趣也可以研究下 vue3-sfc-loader
特性:

  • Supports Vue 3 and Vue 2
  • Only requires Vue runtime-only build
  • Focuses on component compilation. Network, styles injection and cache are up to you
  • Embedded ES6 modules support ( including import() )
  • SFC Custom Blocks support
  • JSX support
  • Support custom CSS, HTML and Script language, see pug and stylus examples
  • Properly reports template, style or script errors through the log callback
  • You can build your own version and easily customize browsers you need to support

Last modification:April 17th, 2021 at 10:46 pm
如果觉得我的文章对你有用,请随意赞赏或留下你的评论~