442 vue内置组件keep-alive:include,配合路由
作者:互联网
11-内置组件02-keepAlive.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!--
component 内置组件
keep-alive 缓存
-->
<div id="app">
<button @click="fn('one')">One</button>
<button @click="fn('two')">Two</button>
<!--
is : 负责显示哪个组件
值 : 组件的名称 , name
-->
<!-- 1. 全部缓存 -->
<!-- <keep-alive>
<component :is="componentName">
<one></one>
<two></two>
</component>
</keep-alive> -->
<!-- 2. 只缓存其中一个 -->
<keep-alive include="one,two">
<component :is="componentName">
<one></one>
<two></two>
</component>
</keep-alive>
</div>
<script src="./vue.js"></script>
<script>
Vue.component('one', {
name: 'one',
template: `<div> 子组件 one: <input> </div>`
})
Vue.component('two', {
name: 'two',
template: `<div> 子组件 two: <input> </div>`
})
const vm = new Vue({
el: '#app',
data: {
componentName: 'one'
},
methods: {
fn(name) {
this.componentName = name
}
}
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 方式1 -->
<!-- <keep-alive>
<router-view></router-view>
</keep-alive> -->
<!-- 方式2 -->
<!-- 需要缓存的,加keep-alive -->
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
<script src="./vue.js"></script>
<script src="./node_modules/vue-router/dist/vue-router.js"></script>
<script>
// 和路由配合的时候,【局部】组件就不需要到 Vue实例 中注册了
const One = {
template: `
<div> 子组件 one: <input> </div>
`
}
const Two = {
template: `
<div> 子组件 two: <input> </div>
`
}
// 实例路由
const router = new VueRouter({
routes: [
{
path: '/one',
name: 'one',
component: One,
meta: { keepAlive: true }
},
{
path: '/two',
name: 'two',
component: Two,
meta: { keepAlive: false }
}
]
})
const vm = new Vue({
router,
el: '#app',
data: {}
})
</script>
</body>
</html>
标签:Vue,const,name,442,two,alive,keep,template,组件 来源: https://www.cnblogs.com/jianjie/p/12693548.html