iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
2
Modern Web

忍住不打牌位,只要30天VueJS帶你上A牌系列 第 7

Day07 今晚我想來點不一樣的動態元件,"is" 屬性

大部分的人在想做動態加載元件都會想到哪種作法?最常使用v-if來達到動態元件效果,如下程式碼

<step1 v-if="currentComponent ==='step1'"></step1> 
<step2 v-else></step2>

https://ithelp.ithome.com.tw/upload/images/20200911/20129187LLMQ6bLDIg.png

今晚我想來點不一樣的汕頭火鍋(欸不是啦,是在 component 中加上"is" 屬性,透過綁定變數值來切換渲染在模板上。
currentComponent 的值應該要元件的名稱,如"step1"、"step2"

<button @click="currentComponent='step1'">step1</button>
<button @click="currentComponent='step2'">step2</button>
<component v-bind:is="currentComponent"></component>

然而切換元件都會摧毀元件並創建新元件,有些情況我們希望在離開元件式能保留資料,不希望被摧毀,而keep alive使用快取是最佳的方式,比如像是問卷,常有下一步/上一步。

keep-alive 提供了兩個 prop 供開發者使用:

include: 注記需要被緩存(cache)的元件名稱 ,意即保留資料(剩下都不保留)
exclude: 注記不需被緩存(cache)的元件名稱 ,意即不保留資料(剩下全部保留)

以上參數可以使用字串、正規表示式、或陣列

在 keep-alive 標籤內的所有組件都會被加上 activated 及 deactivated 鉤子函數,他們觸發在組件啟用及休眠。

#activated:

被 keep-alive 緩存的元件觸發時調用。

#deactivated:

被 keep-alive 緩存的元件停用時調用。

<template>
  <div>
      <keep-alive :include="alive">
        <step1 v-if="currentStep===1"></step1>
        <step2 v-if="currentStep===2"></step2>
        <step3 v-if="currentStep===3"></step3>
        <step4 v-if="currentStep===4"></step4>
      </keep-alive>
      <button @click="next" disabled="currentStep===4">next</button>
      <button @click="back" disabled="currentStep===1">back</button>
  </div>
</template>
<script>
import step1 from './step1'
import step2 from './step2'
import step3 from './step3'
import step4 from './step4'
export default {
  name: 'workflow',
  data () {
    return {
      currentStepName: '黃光',
      currentStep: 1,
      workflowSteps: [
        { stepID: 1, stepName: '黃光' },
        { stepID: 2, stepName: '蝕刻' },
        { stepID: 3, stepName: '薄膜' },
        { stepID: 4, stepName: '擴散' }
      ]
    }
  },
  components: {
    step1, step2, step3, step4
  },
  computed: {
    alive () {
      const stepsName = this.workflowSteps
                              .filter(each => each.stepID <= this.currentStep)
                              .map(e => e.stepName)
      return stepsName
    }
  },
  methods: {
    next () {
      this.currentStep += 1
    },
    back () {
      this.currentStep -= 1
    }
  }

}
</script>

以上程式碼,我們可以看到:
1.定義所有工作流程
2.設定上一步/下一步,與基本防呆
3.在keep-alive標籤加上include屬性綁定alive
4.alive函數保留現在步驟的之前步驟

有任何問題歡迎下方留言,如果喜歡我的文章別忘了按讚、訂閱追蹤加分享唷!

---我是分隔線-----------------------------------------------------------
PollyPO技術-前端設計轉前端工程師-JS踩坑雜記 30 天
喬依司-實作經典 JavaScript 30
五百億-Vue CLI + Firebase 雲端資料庫 30天打造簡易部落格及後臺管理
eien_zheng-前端小嘍嘍的Golang學習旅程_The journey of learning Golang


上一篇
Day06 小夫我要Slot進來了喔,Slot插槽
下一篇
Day08 -上我的異步元件走路要扶牆,異步元件
系列文
忍住不打牌位,只要30天VueJS帶你上A牌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言