JSFiddle - React, Tailwind, and code Playground

by In Roam

HTML

<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js"></script>
<div id="app">
  <keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
  </keep-alive>

  <router-view v-if="!$route.meta.keepAlive"></router-view>
</div>

JavaScript

const A = {
	template: `<div>
  	<p>Page A</p>
    <div>Count: {{ count }} <button @click="plus">+</button></div>
    <router-link to="/b">Go to B</router-link>
  </div>`,
	data () {
  	return {
    	count: 0
    }  
  },
  methods: {
  	plus () {
    	this.count++
    }
  }
}
const B = {
	template: `<div>
  	<p>Page B</p>
    <button	@click="back(true)">返回(缓存)</button>
    <button	@click="back()">返回(不缓存)</button>
  </div>`,
  data () {
  	return {
    	count: 1,
      needCache: false
    } 
  },
  methods: {
  	back (needCache = false) {
			this.needCache = needCache
			this.$router.push({
      	name: 'a'
      })
    }
	},
  beforeRouteLeave (to, from, next) {
  	// 设置 A 的 keepAlive
    to.meta.keepAlive = this.needCache
		next()
  }
}

const routes = [
  { 
  	path: '/',
    name: 'a',
    component: A,
    meta: {
      keepAlive: true // 需要被缓存
    }
  },
  {
  	path: '/b',
    name: 'b',
    component: B,
    meta: {
      keepAlive: false // 需要被缓存
    }
  }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
  router,
}).$mount('#app')