2021 web面试题常见vue之一 keep-alive 0
2021-08-24 本文已影响0人
litielongxx
keep-alive
只在需要缓存组件状态时包裹一下,典型入tab设置中心,切换不同状态还在类似。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
span {
padding:0 5px;
cursor: pointer;
}
span:hover {
border:1px solid #ccc;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!-- 引入样式 -->
<link
rel="stylesheet"
href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
/>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
<h3>keep-alive保持组件缓存状态,典型的为tab切换子项保留切换之前</h3>
<p>
观察打开keep-alive;切换第一个组件选中后返回后状态还在不
</p>
<!-- 注意是v-bindis切换动态组件;-->
<div>
<span @click="name='aa'">组件aa</span>
<span @click="name='bb'">组件bb</span>
</div>
<!-- <keep-alive> -->
<component v-bind:is="name"></component>
<!-- </keep-alive> -->
</div>
</body>
<script>
// 整活几个组件
Vue.component("aa", {
template: `
<el-tabs :tab-position="'left'" v-model="activeName" @tab-click="handleClick">
<el-tab-pane label="用户管理" name="first">用户管理</el-tab-pane>
<el-tab-pane label="配置管理" name="second">配置管理</el-tab-pane>
<el-tab-pane label="角色管理" name="third">角色管理</el-tab-pane>
<el-tab-pane label="定时任务补偿" name="fourth">定时任务补偿</el-tab-pane>
</el-tabs>
`,
data() {
return {
activeName: "second",
};
},
methods: {
handleClick(tab, event) {
console.log(tab, event);
},
},
});
Vue.component("bb", {
template: `
<el-alert
title="今天天气很好"
type="success">
</el-alert>
`,
data() {
return {
activeName: "second",
};
},
methods: {
handleClick(tab, event) {
console.log(tab, event);
},
},
});
var app = new Vue({
el: "#app",
data() {
return {
name:'aa'
};
},
methods: {},
});
</script>
</html>