Vue中的组件切换时不销毁

问题描述

写了一个流程类应用,模板都是复用的,假设有3种类型模板切换,如果连续两个同样模板则出现模板缓存不会销毁的问题

相关代码

精简代码如下

<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()
    }
  }
})

切换不同组件才会完全销毁之前的变量,如果切换同一组件,是不会销毁组件。试过每次点击后初始化变量。但是实际场景不通用。

阅读 12.9k
2 个回答
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>

楼下的方法好点,报错的话 给button或者component外面裹个div 就没有报错了

给每个组件一个不同的 key, 这样相同的组件也会能被区分开.

<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()
    }
  }
})
推荐问题