鍍金池/ 問答/Linux  HTML/ Vue中的組件切換時(shí)不銷毀

Vue中的組件切換時(shí)不銷毀

問題描述

寫了一個(gè)流程類應(yīng)用,模板都是復(fù)用的,假設(shè)有3種類型模板切換,如果連續(xù)兩個(gè)同樣模板則出現(xiàn)模板緩存不會(huì)銷毀的問題

相關(guān)代碼

精簡代碼如下

<div id="dynamic-component-demo">
  <button v-for="tab in tabs" v-bind:key="tab" @click="currentTab = tab">{{ tab }}</button>
  <component :is="currentTabComponent" ></component>
</div>
Vue.component('tab-posts', {
  data: function() {
    return {
            args:'',
    }
  },
  template:'<div><input type="text" v-model="args"></div>',
})

Vue.component('tab-archive', {
  template: '<div>Archive component</div>'
})

new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Posts',
    tabs: ['Posts', 'Posts', 'Archive', 'Posts']
  },
  computed: {
    currentTabComponent: function() {
      return 'tab-' + this.currentTab.toLowerCase()
    }
  }
})

切換不同組件才會(huì)完全銷毀之前的變量,如果切換同一組件,是不會(huì)銷毀組件。試過每次點(diǎn)擊后初始化變量。但是實(shí)際場景不通用。

回答
編輯回答
糖果果

給每個(gè)組件一個(gè)不同的 key, 這樣相同的組件也會(huì)能被區(qū)分開.

<button v-for="(tab, index) in tabs" v-bind:key="index" @click="currentTabIndex = index">{{ tab }}</button>
<component :is="currentTabComponent" :key="currentTabIndex" ></component>


new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTabIndex: 0,
    tabs: ['Posts', 'Posts', 'Archive', 'Posts']
  },
  computed: {
    currentTabComponent: function() {
      return 'tab-' + this.tabs[currentTabIndex].toLowerCase()
    }
  }
})
2017年8月7日 09:29
編輯回答
悶騷型
new Vue({
  el: '#dynamic-component-demo',
  data: {
    currentTab: 'Posts',
    tabs: ['Posts', 'Posts', 'Archive', 'Posts'],
    currentTabComponent: 'tab-posts'
  },
  computed: {
    
  },
  methods: {
      changeTab (tab) {
        this.currentTab = tab
      this.currentTabComponent = ''
      this.$nextTick(() => {
          this.currentTabComponent = 'tab-' + this.currentTab.toLowerCase()
      })
      
    }
  }
})
<div id="dynamic-component-demo">
  <button v-for="(tab, index) in tabs" v-bind:key="index" @click="changeTab(tab)">{{ tab }}</button>
  <component :is="currentTabComponent" ></component>
</div>

樓下的方法好點(diǎn),報(bào)錯(cuò)的話 給button或者component外面裹個(gè)div 就沒有報(bào)錯(cuò)了

2017年6月5日 15:19