动态组件
- 什么是动态组件?
可以改变的组件 - 使用
通过Vue提供一个component+is属性 - 动态组件指的就是component这个组件
- 案例-业务:点击一个按钮进行组件的切换
<div id="app">
<button @click="change">切换</button>
<keep-alive include="">
<component :is="type"></component>
</keep-alive>
</div>
<script>
Vue.component('Aa',{
template:'<div>Aa</div>'
})
Vue.component('Bb',{
template:'<div>Bb</div>'
})
new Vue({
data:{
type:Aa
},
method:{
change(){
this.type=(this.type==='Aa'?'Bb':'Aa')
}
}
}).$mount('#app')
</script>
- Vue提供了一个keep-alive的组件可以将我们的组件进行浏览器缓存,这样当我们切换组件时,就可以大大提高使用效率
- keep-alive也可以使用属性的形式呈现,但是如果我们搭配component的话,建议使用组件的形式。
插槽slot
- 作用/概念:预先将将来要使用的内容进行保留
- 具名插槽:给slot取个名字
- 注意:以上两种形式在vue2.6以上被废弃
- 为什么要用v-slot指令来代替呢?
- 将具名插槽和作用域插槽进行统一
- 要将这两个属性带有vue的标志,并且符合vue两个最大的特性之一:指令的概念
- 建议:新的v-slot要掌握,旧的也掌握吧。
- 案例:
<div id="app">
<!--Hello组件-->
<Hello>
<div>
这是填补内容
</div>
</Hello>
</div>
<!--template-->
<template id="hello">
<div>
<slot></slot>
<h3>this is Hello</h3>
</div>
</template>
<script>
Vue.componnet('Hello',{
template:'#hello'
})
new Vue({
el:'#app'
})
</script>
- 具名插槽
<div id="app">
<Hello>
<header slot="header">this is header</header>
<footer slot="footer">this is footer</footer>
</Hello>
</div>
<template id="hello">
<div>
<slot name="header"></slot>
<h3>this is content</h3>
<slot name="footer"></slot>
</div>
</template>
<script>
Vue.component('Hello',{
template:'#hello'
})
new Vue({
}).$mount('#app')
</script>
- v-slot (vue 2.6)
- 案例:
<div id="app">
<Hello>
<template v-slot="header">
<h1>this is title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot="footer">
<h1>this is footer</h1>
</template>
</Hello>
</div>
<template id="hello">
<div class="container">
<header>
<slot name="header"></slot>
</header>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<script>
Vue.component('Hello',{
template: '#hello'
})
new Vue({
el: '#app',
})
</script>
div>