天天看點

Vue 傳回上一頁頁面不重新整理在中間頁面就行判斷

Vue 傳回上一頁頁面不重新整理

場景:首頁點進清單頁時要重新整理資料,資訊頁傳回清單頁時不重新整理資料

首先在router.js中配置

{
			path: '/home',
			name: 'home',
			meta: {
				title: '首頁',
			},
			component: () => import('./views/home/index.vue'),
		},
		{
			path: '/info/:id',
			name: 'info',
			meta: {
				title: '資訊',
				keepAlive: true,///此元件需要緩存
				isBack: false,//用來判斷是否是傳回上一頁
			},
			component: () => import('./views/home/info.vue'),
		},
		{
			path: '/home/view',
			name: 'view',
			meta: {
				title: '詳情',
			},
			component: () => import('./views/home/view.vue'),
		},
           

在App.vue中設定需要緩存的頁面

<keep-alive>
      <router-view v-if="$route.meta.keepAlive" class="Router" ></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" class="Router" ></router-view>
           

在中間頁面就行判斷

beforeRouteEnter(to, from, next) {
    //from從哪個頁面過來的資訊
    //to 到哪個頁面來
    console.log(to)
    console.log(from)
    //用來判斷是否緩存
    if (from.name === 'view') {
      to.meta.isBack = true
    }
    if (from.name === 'home') {
      to.meta.isBack = false
    }
    next()
  },
  //如果不設定keepAlive:beforeRouteEnter--》created--》  mounted--》destroyed
  //因為設定了keepAlive第一次進入時keepAlive會運作beforeRouteEnter--》activated--》created--》  mounted--》deactivated
  //第二次進入時隻會運作beforeRouteEnter--》activated--》deactivated
  activated() {
    if (!this.$route.meta.isBack) {beforeRouteEnter--》activated--》created--》  mounted
      const { id } = this.$route.params
      this.id = id
      this.loadData()
    }
  },