1. 程式人生 > >Vue-元件

Vue-元件

元件是Vue最強大的功能之一,那麼到底什麼是Vue元件呢?通俗點說就是一個自定義標籤

Vue元件的分類:全域性元件(在任何Vue例項中均可以使用)和區域性元件(只有在當前Vue例項中使用);

全域性元件的定義方式:

方式一: 建立組建構造器,然後再由元件構造器建立元件(不常用),例如:

//1.使用Vue.extened()方法建立元件構造器
                var myComponent = Vue.extend({
                    template:"<h3>我的第一個元件</h3>",
                })
                //2.使用Vue.component("元件名",元件構造器),根據元件構造器來建立元件,
                Vue.component("hello",myComponent);
方式二:直接建立元件,使用Vue.component("元件名",{templa..等選項});Vue元件名建議使用小寫字母加“-”的方式

Vue.component("my-world", {
                    template: "<h3>{{name}}</h3>"//模板
                })
區域性元件的定義方式:

只有一種定義方式,使用Vue例項中的components選項,例如:

var app1 = new Vue({
                    el: "#container1",
                    components: {//區域性元件
                        "hi-world":{
                            template:'<h3>{{name}}</h3>',
                            data:function(){//在元件中儲存資料的時候,必須以函式的形式,函式返回一個物件
                                return {//返回的也是一個物件
                                    name:"alice"
                                }
                            }
                        }
                    }
                })
自定義元件中的資料,其實Vue例項本身也是一個元件(根元件),其有一個data選項來儲存資料,那麼自定義元件有沒有類似的選項呢,答案是有的,只不過和Vue例項的寫法有些區別:

var app1 = new Vue({
                    el: "#container1",
                    components: {//區域性元件
                        "hi-world":{
                            template:'<h3>{{name}}</h3>',
                            data:function(){//在元件中儲存資料的時候,必須以函式的形式,函式返回一個物件
                                return {//返回的也是一個物件
                                    name:"alice"
                                }
                            }
                        }
                    }
                })
Vue元件的使用:既然說組建是一個自定義標籤,那麼他就應該以標籤的方式來用,例如:

<div id="container">
            <hello></hello>
            <my-world></my-world>//
            <hi-world></hi-world>//<h3>alice</h3>
            <!-- 區域性元件 -->
        </div>
        <div id="container1">
            <my-world></my-world>
             <hi-world></hi-world>   //<h3>alice</h3>
             <!-- 區域性元件 -->
        </div>