不使用构建工具的vue组件书写方式

发布时间 2023-10-27 15:49:57作者: Easy C#

将vue组件转换为普通的js文件(IIFE)

先写个简单的component

export default {
  data() {
    return { count: 0 }
  },
  template: `<button @click="count++">You clicked me {{ count }} times.</button>`
}

我们把这个组件保存为mycomponent.js

使用时,是这样的

<div id="app">
        <div>{{ message }}</div>
        <my-component></my-component>
    </div>
    <script type="module">
        import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
        import MyComponent from '/component/my-component.js'
        var app = createApp({
            components:{MyComponent},
            data () {
                return {
                    message:"Hello Vue"
                }
            }
        });
        app.mount('#app')
    </script>

这样写的组件,是使用了ESM标准的,无法使用<script src='...' />这种方式使用,如果想转换成IIFE方式,那么就把他直接复制给一个变量即可。

var MyComponent = (function () {
    return {
        data() {
            return {count: 0}
        },
        template: `<button @click="count++">You clicked me {{ count }} times.</button>`
    }
})()

这样就可以直接使用了

<div id="app">
<my-component></my-component>
</div>
<script src="/component/my-component.js"></script>
<script>
var app = Vue.createApp({ data () {return {message:'helloword'}}})
//重点是下面这行
app.component('MyComponent',MyComponent);
app.mount("#app")
</script>

不用构建工具,也可以使用组件。