在html中通过vue3-sfc-loader引用.vue文件
Vue

在html中通过vue3-sfc-loader引用.vue文件

binscor
2023-03-06 / 0 评论 / 1,444 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年03月06日,已超过509天没有更新,若内容或图片失效,请留言反馈。

vue3-sfc-loader

通过html的方式直接使用vue的问题已解决,但是在html中如何引用.vue就需要借助一些其他手段了。vue3-sfc-loader可以将vue文件编译之后再引入到当前的html中,它既支持vue2也支持vue3;以下是vue3和elementPlus为例,将.vue文件引入到html中。

html

<!DOCTYPE html>
<head>
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/element-plus/dist/index.css"/>
  <script src="//cdn.jsdelivr.net/npm/vue@3"></script>
  <script src="//cdn.jsdelivr.net/npm/element-plus"></script>
  <script src="https://cdn.jsdelivr.net/npm/vue3-sfc-loader@0.8.4/dist/vue2-sfc-loader.js"></script>
</head>
<body>
  <div id="app">
    <my></my>
  </div>
</body>
  <script type="module">
    const { loadModule } = window['vue3-sfc-loader'];
    const options = {
      moduleCache: {
        vue: Vue
      },
      async getFile(url) {
        const res = await fetch(url);
        if ( !res.ok )
          throw Object.assign(new Error(res.statusText + ' ' + url), { res });
        return {
          getContentData: asBinary => asBinary ? res.arrayBuffer() : res.text(),
        }
      },
      addStyle(textContent) {
        const style = Object.assign(document.createElement('style'), { textContent });
        const ref = document.head.getElementsByTagName('style')[0] || null;
        document.head.insertBefore(style, ref);
      },
    }
    const app = Vue.createApp({
      components: {
        'My': Vue.defineAsyncComponent(() => loadModule('./My.vue', options))
      }
    });
    app.use(ElementPlus);
    app.mount('#app');
  </script>
</html>

My.vue

<template>
    <div class="hello">Hello {{who}}</div>
</template>
 
<script>
module.exports = {
    data: function() {
        return {
            who: 'world'
        }
    }
}
</script>
 
<style>
.hello {
    background-color: #ffe;
}
</style>
0

评论 (0)

取消