鍍金池/ 問答/HTML/ Vue中多個路由共享一個組件,如何避免組件被緩存?

Vue中多個路由共享一個組件,如何避免組件被緩存?

這是我的Route, A和B公用組件Common。

let routes = [
  {
    path: '/A',
    name: 'A',
    component: Common,
  },
  {
    path: '/B',
    name: 'B',
    component: Common,
  }
];

Common組件的代碼如下。我點擊了幾次button后,跳轉(zhuǎn)到B,transition不生效,而且顯示的是更改過的number值。如何避免緩存讓Common組件重新渲染?

<template> 
     <div>
         <button @click="click"> Click Me!</button>
         <br>
         The value of number is: {{number}}
         <br>
         <button @click="next">Click Me to navigate to next route!</button> 
     </div>
</template>

<script>
// @ is an alias to /src
import _ from 'lodash';
export default {
  name: 'Common',
   data: function() {
    return {
        number: 1
    }
  },
  methods: {
     click: function() {
         this.number++;
     },
     next: function() {
         this.$router.push({path: 'B'});
     }
  },
  mounted: function() {
    console.log('enter mounted');
  },
  destroyed: function() {
      console.log('destroyed');
  }
}
</script>


Update:
我發(fā)現(xiàn)可以在Common組件中加入如下方法,這樣當(dāng)從A跳到B的時候,B中的數(shù)據(jù)就是原始的數(shù)據(jù),但目前還有一個問題,transition還是沒有起作用,要怎么解決呢。。。

beforeRouteLeave: function(to, from, next) {
      console.log('beforeRouteLeave');
      Object.assign(this.$data, {number: 1});
      next();
}
回答
編輯回答
乖乖瀦

給組件加一個key

2018年7月15日 18:39
編輯回答
裸橙
:key = "handleDate()"

handleDate(){
    return new Date().getTime()
}
2017年12月29日 00:54