iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 17
0
自我挑戰組

Vue 學習筆記 - 讓你30天掌握 Vue系列 第 17

Day 17 : 動態切換元件

動態切換元件

今天來點輕鬆的,其實是我最近比較累所以沒辦法打太多東西,所以來介紹一個簡單的元件動態切換的方式,之前有使用動態的方式來切換 className 還記得嗎?今天的內容跟它非常像,但是我們是切換要顯示的元件,來看範例:

<div id="app">
  <primary-component :data="msg">{{data}}</primary-component>
</div>

<script type="text/x-template" id="primaryComponent">
  <div class="primary">
    <h2>{{data}}</h2>
  </div>
</script>
Vue.component('primary-component', {
    props: ['data'],
    template: '#primaryComponent'
})
new Vue({
    el: '#app',
    data: {
      msg: 'Hello Vue !!',
      current: 'primary-component'
    }
})

上面的元件建立方式應該已經很熟悉了,如果還不熟悉的話可以看前幾天的文章,都是在講元件的唷!接下來我要將元件掛載的方式改為使用 is ,就會變下面這樣:

<div id="app">
    <div is="primary-component" :data="msg"></div>
</div>

這在前幾天的文章也有提到過,那麼要怎麼使用動態的方式切換元件呢?我先再來增加一個元件如下:

<script type="text/x-template" id="dangerComponent">
  <div class="danger">
    <h2>{{data}}</h2>
  </div>
</script>
Vue.component('danger-component', {
    props: ['data'],
    template: '#dangerComponent'
})

跟上面的元件只有 class 的屬性不一樣而已,至於 CSS 的內容我就不放上來囉!就只是單純的顏色不同而已,接下來我要來利用上面所建立的 current 的值來切換不同的元件,我相信聰明如你應該已經想到方法了。

<div id="app">
  <button @click="current = 'primary-component'">Primary</button>
  <button @click="current = 'danger-component'">Danger</button>
  <div :is="current" :data="msg"></div>
</div>

首先我們先建立兩個按鈕如上,再來將 is 綁定 data 裡的 current 的值,再來就利用按鈕的點擊事件來變更 current 的值就可以達到動態切換元件的效果了唷!

那麼,明天再見囉!


上一篇
Day 16 : 元件插槽 Slot
下一篇
Day 18 : Vue extend
系列文
Vue 學習筆記 - 讓你30天掌握 Vue31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言