通过 CDN 引入来使用 vue3-easy-data-table

730 阅读1分钟

Steps

  1. 引入!

截屏2022-07-03 下午10.17.21.png

  1. 使用!

截屏2022-07-03 下午10.17.10.png

  1. awesome!

截屏2022-07-03 下午10.24.08.png

ES module or UMD?

项目的 build tool 用的 vite ,打包出 xxxx.es.js(ES module 格式)和 xxxx.umd.js(UMD 格式)两种结果,本来想推荐在浏览器中通过 script 标签引入 CDN 的 ES module 文件并且使用的,就像下面这样:

<link href="https://unpkg.com/vue3-easy-data-table/dist/style.css" rel="stylesheet">

<body>
    <div id="app">
        <easy-data-table :headers="headers" :items="items" />
    </div>
    
    <script type="importmap">
        { 
            "imports": {
                "vue": "https://cdn.jsdelivr.net/npm/vue@3.2.1/dist/vue.global.js",
                "vue3-easy-data-table": "https://unpkg.com/vue3-easy-data-table", 
            } 
         }
     </script>
     
     <script type="module">
         import { createApp } from 'vue';
         import Vue3EasyDataTable from 'vue3-easy-data-table';
         const App = createApp({ 
             components: { EasyDataTable: Vue3EasyDataTable, }, 
             data () { 
                 return { 
                     headers:[ { text: "PLAYER", value: "player" }, { text: "TEAM", value: "team"}, { text: "NUMBER", value: "number"}, { text: "POSITION", value: "position"}, { text: "HEIGHT", value: "indicator.height"}, { text: "WEIGHT (lbs)", value: "indicator.weight", sortable: true}, { text: "LAST ATTENDED", value: "lastAttended", width: 200}, { text: "COUNTRY", value: "country"}, ],
                     items: [ { player: "Stephen Curry", team: "GSW", number: 30, position: 'G', indicator: {"height": '6-2', "weight": 185}, lastAttended: "Davidson", country: "USA"}, { player: "Lebron James", team: "LAL", number: 6, position: 'F', indicator: {"height": '6-9', "weight": 250}, lastAttended: "St. Vincent-St. Mary HS (OH)", country: "USA"}, { player: "Kevin Durant", team: "BKN", number: 7, position: 'F', indicator: {"height": '6-10', "weight": 240}, lastAttended: "Texas-Austin", country: "USA"}, { player: "Giannis Antetokounmpo", team: "MIL", number: 34, position: 'F', indicator: {"height": '6-11', "weight": 242}, lastAttended: "Filathlitikos", country: "Greece"}, ], 
                 }
             }, 
         });
        if (document.getElementById('app')) { App.mount('#app') }
    </script>
 </body>

不过 safari, firefox 等浏览器都还不支持importmap的用法:caniuse.com/?search=imp… 所以还是用了老办法,在打包入口文件 index.ts 中检测浏览器 vue 环境并全局注册 Vue3EasyDataTable 组件,github.com/HC200ok/vue…

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.createApp({}).component('Vue3EasyDataTable', DataTable);
}

然后使用的时候通过window['vue3-easy-data-table']获取。

文档

hc200ok.github.io/vue3-easy-d…

如有建议或需求,欢迎提 issue ,项目地址: github.com/HC200ok/vue…

如果觉得还不错,欢迎给我一个 github⭐支持我一下,谢谢!