vue中的 动态class 动态组件 keep-alive
这里是knockey, 这是我需要做笔记的知识点们, 从2021年12月11日开始
1. 动态class
<button
v-for="tab in tabs"
:key="tab"
:class="['tab-button', { active: currentTab === tab }]"
@click="currentTab = tab"
>
{{ tab }}
</button>
.tab-button {
padding: 6px 10px;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
border: 1px solid #ccc;
cursor: pointer;
background: #f0f0f0;
margin-bottom: -1px;
margin-right: -1px;
}
.tab-button:hover {
background: #e0e0e0;
}
.tab-button.active {
background: #e0e0e0;
}
分析:
在有多个class,需要静态动态混合使用时,可以将class写为数组。静态的引号引起来表示为静态,动态的可以用大括号括起来,里面可以写表达式,表达式的写法要注意,多个class之间用逗号分隔。另外class前面要加: 修饰符!
2. 动态组件
<component :is="currentTabComponent" class="tab"></component>
- 断联
<div id="example">
<button @click="change">切换页面</button>
<keep-alive>
<component :is="currentView"></component>
</keep-alive>
new Vue({
el: "#example",
data:{
index: 0,
attrs:["page1","page2","page3"]
}
,components: {
page1:{template:`<div>组件页1</div>`},
page2:{template:`<div>组件页2</div>`},
page3:{template:`<div>组件页3</div>`},
},methods:{
change:function () {
const len = this.attrs.length
this.index = (++this.index)%len
}
},computed:{
currentView:function () {
return this.attrs[this.index]
}
}
})
3. keep-alive
- 这就是为什么组件要写name的原因
- include 属性用来指定:只有名称匹配的组件会被缓存。多个组件名之间使用英文的逗号分隔:
include- 字符串或正则表达式。只有名称匹配的组件会被缓存。exclude- 字符串或正则表达式。任何名称匹配的组件都不会被缓存。max- 数字。最多可以缓存多少组件实例。
<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
<!-- 正则表达式 (使用 v-bind) -->
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
<!-- Array (use v-bind) -->
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>
- 如果想重新进来(暂时出去)的时候执行一些操作呢?
- 两个生命周期钩子
activated和deactivated activated- 被 keep-alive 缓存的组件激活时调用。
- 该钩子在服务器端渲染期间不被调用。
deactivated- 被 keep-alive 缓存的组件失活时调用。
- 该钩子在服务器端渲染期间不被调用。