iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 18
0
Modern Web

Vue.js 30天系列 第 18

Vue.js 18 - 組件/元件(Component) - 組件掛載及限制

使用組件有三個步驟

  1. 宣告建構子(Constructor)
  2. 註冊組件(Regist Component)
    2.5 建立組件(Create Component)
  3. 掛載組件(Mount Component)

前兩項已經介紹過,也可以簡化成一個步驟。

<script>
Vue.component('example', require('./components/Example.vue'));

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

介紹最後一項 - 組件掛載(mount)
先複習一下,透過模板(template)的基本掛載法

<div id="app">
    <!-- Instance 掛載兩個 example 組件 -->
    <example id="1"></example>
    <example id="2"></example>
</div>

真實情況可能不只一種組件,需要依照情況掛載

<script>
Vue.component('viewer', require('./components/Example.vue'));
Vue.component('editor', require('./components/Editor.vue'));

var app = new Vue({
    el: '#app',
    data: {
        state: 'viewer'
    },
    methods: {
        toggle: function() {
            return (this.state === 'viewer') ? 'editor' : 'viewer';
        }
    }
});
</script>

透過is屬性動態掛載,按當時情境決定,絕對實用。

<div id="app">
    <button type="button" @click="toggle">{{ state }}</button>
    <div is="state"></div>
    <div is="state"></div>
    
    <!-- state: 'viewer' -->
    <!--
    <viewer></viewer>
    <viewer></viewer>
    -->
    
    <!-- state: 'editor' -->
    <!--
    <editor></editor>
    <editor></editor>
    -->
    
</div>

如果你有興趣的話,可以延伸到vue-router換頁面的機制。


最後補充進階的手動掛載 - 透過Vue建構子 或 $mount API
官方文件寫得很清楚,你可以透過已宣告的建構子,掛載新的組件。

<!-- 宣告建構子 -->
var Example = Vue.extend({
  template: '<div>Here is Example</div>'
});
  1. 透過建構子掛載
<!-- 這會把#app內容完全換掉 -->
new Example({ el: '#app' })

掛載前的等效樣板

<div id="app">
    <example></example>
    <example></example> 
</div>

掛載後

<div id="app">
    <!-- 前面兩個 <example> 都不見了 -->
    <example></example>
</div>

  1. $mount掛載點
new Example().$mount('#app');

跟(1)相同,完全換掉#app內容


當你加上新的組件,又不想蓋掉原內容,參考這種做法
3. 不給$mount掛載點
當你不指定時,$mount會把產生的新組件掛在document之外(畫面上看不到)。

var example3 = new Example().$mount()
document.getElementById('app').appendChild(example3.$el)
<div id="app">
    <example></example>
    <example></example>
    <!-- 新產生的組件 -->
    <example></example>
</div>

但這種做法並不推薦,畢竟Vue是data-driven,能夠避免直接操作DOM,就盡量避免。


上一篇
Vue.js 17 - 生命週期(Lifecycle)
下一篇
Vue.js 19 - 組件/元件(Component) - 其他補充
系列文
Vue.js 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
olivermode
iT邦新手 3 級 ‧ 2023-05-31 17:03:06

手誤多留言一次 請幫刪

我要留言

立即登入留言