iT邦幫忙

1

Vue 之溫習 component 的世界 - 1

最近又再重複的溫習了 Vue 的 component,希望能重新幫自己整理思緒

component 俗稱元件,在網頁我們每一個區塊內容都可以封裝成一個獨立的元件,而元件還可以再包覆其他元件,有點類似 HTML 的標籤還可以再包覆標籤的概念是一樣的。

建立 component

而在 Vue 裡面,建立 component 有分為區域性跟全域性:

區域性的建立如下:

const child = {
    teamplate: '',
    props: [],
}

const app = new Vue({
    el: '#app',
    data: {},
    components: {
        'my-component': child
    }
});

而全域性,則是採用了 Vue.component() 的方法:

Vue.component('my-component', {
    template: '',
    props: [],
});

而兩者的差別在於,當今天有兩個 Vue 實體時,全域性的 component 可以被重複利用,但區域性的 component 則無法,下面採用了全域的 component 建立,所以在 app2 內 my-conponent 是可以被運作的:

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

<div id="app2">
    <my-component></my-component>
</div>

<script>
    Vue.component('my-component', {
        template: '<div>Hello</div>'
    });

    const app = new Vue({
        el: '#app',
    });
    
    const app2 = new Vue({
        el: '#app2',
    });
</script>

如果改成區域性:

<script>
    const child = {
        template: '<div>Hello</div>'
    };
    
    const app = new Vue({
        el: '#app',
        components: {
            'my-component': child
        }
    });
    
    const app2 = new Vue({
        el: '#app2',
    });
</script>

我們僅在 app 內的 components 調用了 child 這個變數,並沒有也在 app2 內也調用,所以此時 app2 內的 my-component 是會出現錯誤的通知

data function return

接著如果我們建立 component 時,要使用 data 這個方法時,需使用 function return,這是避免跟 Vue 實體的資料衝突:

Vue.component('myComponent', {
    template: '<button @click="counter ++"></button>'
});

const app = new Vue({
    el: '#app',
    data: {
        counter: 0,
    }
});

如果這樣寫,Vue.component() 內並無使用 data function return,當 button 被點擊時,是直接更改 Vue 實體的資料的,避免這樣的情形,所以要改成如下:

Vue.component('myComponent', {
    template: '<button @click="counter ++"></button>',
    data: function(){
        return {
            counter: 0
        }
    }
});

x-template 封裝 HTML

前面我們建立 component 時,所使用的 template 屬性,都是直接賦予 HTML 內容,但今天如果 HTML 內容太多的時候,就會顯得畫面太亂太過於複雜,所以這個時候我們就可以使用 x-template 來封裝 HTML 的內容,並且我們直接用 id 呼叫即可:

<script type="text/x-template" id="my-component">
    <div class="card">
        ...
    </div>
</script>

<script>
    Vue.component('my-component', {
        template: '#my-component'
    });
</script>

在 template 呼叫 x-template 的 id 即可
這裡要注意一個小重點,x-template 內最外層僅只能有一個節點


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

我要留言

立即登入留言