ワイズリマインダー

【Vue3】単一コンポーネントを読み込むテンプレ

■<head>

<script src="https://cdn.jsdelivr.net/npm/vue@3.2.45/dist/vue.global.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="index.js"></script>

 

■<body>

<div id="app">
 <my-compo></my-compo>
</div>

 

■index.js

'use strict';
(function($){
  $(document).ready(function(){
    objApp.ready();
  });


  let objApp = (function(){
    return{
      'ready': function(){
        this.vue = this.create();
      },

      /*
       * インスタンスの作成
       */
      'create': function(){
        const { loadModule } = window['vue3-sfc-loader'];
        return Vue.createApp({
          data(){
            return{
              datas: []
            }              
          }
         ,components: {
            'my-compo': Vue.defineAsyncComponent( () => loadModule('my-compo.vue', objApp['loaderOption']() ) )
          }
        }).mount('#ysExplorer');
      },
      
      /*
       * vue3-sfc-loader
       */
      'loaderOption': function(){
        return {
          moduleCache: { vue: Vue }
         ,getFile(url){
            url = /.*?\.js|.mjs|.css|.less|.vue$/.test(url) ? url : `${url}.vue`;
            const type = /.*?\.js|.mjs$/.test(url) ? ".mjs" : /.*?\.vue$/.test(url) ? ".vue" : /.*?\.css$/.test(url) ? ".css" : ".vue";
            const getContentData = (asBinary) => fetch(url).then((res) => !res.ok ? Promise.reject(url) : asBinary ? res.arrayBuffer() : res.text() );
            return { getContentData: getContentData, type: type };
          }
         ,addStyle(textContent) {
            let styleElement = document.createElement("style");
            document.head.insertBefore(
              Object.assign(styleElement, { textContent })
             ,document.head.getElementsByTagName("style")[0] || null
            );
          }
         ,handleModule(type, getContentData, path, options) {
            switch (type) {
                case ".css":
                    return options.addStyle(getContentData(false));
                case ".less":
                    console.error(".......");
            }
          }
         ,log(type, ...args) { console.log(type, ...args); }
        };
      },
    }
  })();
})(jQuery);

 

■my-compo.vue

<!--
 ******************************
 *
 * template
 *
 ****************************** -->
<template>
 <p>{{ xyzzy }}</p>
</template>




<!--
 ******************************
 *
 * script
 *
 ****************************** -->
<script scoped>
export default {
  data() {
    return{
      xyzzy: 'Hello World!'
    }
  }
}
</script>


<!--
 ******************************
 *
 * style
 *
 ****************************** -->
<style scoped>
p.xyzzy {
  color: red;
}
</style>

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

検索

最近のコメント

最近の投稿

タグ

フィード配信

アーカイブ

外部リンク