vue建立組件的幾種方法

<html>

<head>
    <title>vue建立組件</title>
    <meta charset="utf-8">
</head>

<body>
    <div id="app">
        <my-com1></my-com1>
        <my-com2></my-com2>
        <my-com3></my-com3>
    </div>
    <div id="app2">
        <private></private>
    </div>
    <template id="temp1">
        <div>
            <h3>這是經過template元素在外部定義的組件結構</h3>
        </div>
    </template>
    <template id="temp2">
        <div>
            <h3>這是一個私有組件</h3>
        </div>
    </template>
</body>
<!-- 這裏請引入cdn或者是下載到本地的vue.js -->
<script src="node_modules\vue\dist\vue.js"></script>
<script>
    //ps:組件模板只能有一個根元素
    //1、建立全局的組件
    //方式1 使用中間變量
    //1.1使用extend建立
    var com1 = Vue.extend({
        template:'<h3>這是使用Vue.extend建立的組件</h3>'
    })
    //1.2使用Vue.component(),定義組件的名稱
    Vue.component('myCom1',com1);//使用駝峯命名是則在引用時就需將大寫的字符變爲小寫,並以-鏈接兩個單詞,不使用則引用時標籤名與定義一致
    //方式2 不使用中間變量
    Vue.component('myCom2',Vue.extend({
        template:'<h3>這是使用Vue.component建立的組件</h3>'
    }))
    //更簡潔的方式
    Vue.component('mycom2',{
        template:'<h3>這是使用Vue.extend建立的組件</h3>'
    })
    // 方式3 經過在template元素,在被控制的#app外面定義組件的模板
    Vue.component('myCom3',{
        template:'#temp1'
    })
    let vm = new Vue({
        el: "#app",
        data:{

        }
    });
    //2、建立私有組件
    let vm2 = new Vue({
        el: "#app2",
        data:{

        },
        components:{
            private:{
                template:"#temp2"
            }
        }
    });
</script>

</html>

  效果:html

相關文章
相關標籤/搜索