Vue 路由緩存


問題 在路由切換時不需要每次 點擊都刷新子路由   尤其是在form表單的情況下  不能讓用戶 輸入一半之后點擊其他頁面  再點回來 表單數據不見了

解決方案  

  vue 2.0     之中  有keep-alive   詳情 見Vue 官網  

 

 

<keep-alive>
<router-view :key="key"></router-view>
</keep-alive>

如果想要這個  單個子路由 不刷新    只需要控制 key    key值不變 緩存   一直存在   想要路由刷新 將key值  改為  前面沒有的

<template>
  <section class="app-main">
    <transition name="fade" mode="out-in">
    	
       <keep-alive>
      		<router-view :key="key"></router-view>
       </keep-alive>
    </transition>
  </section>
</template>

<script>
export default {
  name: 'AppMain',
  computed: {
    key() {
    	if(this.$route.name==undefined&& this.$route.path=='/home'){
    		//頁面第一次加載時 清空 tab 標簽頁上的所有標簽 回到首頁
    	   this.$store.dispatch('delAllViews')
    	}
    	let onlykey = ''
    	let clicked = ''
    	if(!this.$route.meta.clicked){
    		 onlykey = this.$route.path +"0"
    		 clicked = '0'
    	}
    	else{
    		//上一次的狀態為0
    		if(this.$route.meta.clicked=='0'){
    			//這一次有參數
    			if(Object.keys(this.$route.query).length!=0 || this.$route.hash=='#new'){
    				onlykey = this.$route.path +"1"
    				 clicked = '1'
    			}
    			//這一次無參
    			else{
    				onlykey = this.$route.path +"0"
    				 clicked = '0'
    			}
    		}
    		//上一次的狀態不是0 
    		else{
    			//這一次有參數 
    			//在創建新活動時  傳入 hash  = new 
    			if(Object.keys(this.$route.query).length!=0 || this.$route.hash=='#new'){
    				//這一次的狀態     為上一次+1
    				//獲取上一次的狀態 
    				clicked = (parseInt(this.$route.meta.clicked)+1).toString();
    				onlykey = this.$route.path +clicked
    				
    			}
    			//這一次無參 這一次狀態不變
    			else{
    				clicked = parseInt(this.$route.meta.clicked).toString();
    				onlykey = this.$route.path +clicked;
    				
    			}
    		}
    	}
    	this.$route.meta.clicked = clicked;
      return  onlykey 
    }
  },
  
  
}
</script>

  代碼僅供參考  (業務比較復雜 寫了一大推邏輯)!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM