通过插槽来分配内容
一些情况下我们会希望能和 HTML 元素一样向组件中传递内容:
<AlertBox>
传入的内容
</AlertBox>
我们期望能渲染成这样:
这可以通过 Vue 的自定义 <slot> 元素来实现:
<template>
<div class="alert-box">
<strong>子组件自有内容</strong>
<br/>
<slot />
</div>
</template>
<style scoped>
.alert-box {
color: #666;
border: 1px solid red;
border-radius: 4px;
padding: 20px;
background-color: #f8f8f8;
}
strong {
color: red;
}
</style>
使用 <slot> 作为一个占位符,父组件传递进来的内容就会渲染在这里。
<script>
import AlertBox from './AlertBox.vue'
export default {
components: { AlertBox }
}
</script>
<template>
<AlertBox>
传入的内容
</AlertBox>
</template>
动态组件
有些场景会需要在两个组件间来回切换,比如 Tab 界面:
三个子组件代码
<template>
<div class="tab">
Home component
</div>
</template>
<template>
<div class="tab">
Posts component
</div>
</template>
<template>
<div class="tab">
Archive component
</div>
</template>
App.vue 中样式
<style>
/*每个页面公共css */
.demo {
font-family: sans-serif;
border: 1px solid #eee;
border-radius: 2px;
padding: 20px 30px;
margin-top: 1em;
margin-bottom: 40px;
user-select: none;
overflow-x: auto;
}
.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;
}
/* :是伪类,伪类选择元素基于的是当前元素处于的状态,或者说元素当前所具有的特性,
而不是元素的 id class 属性等静态的标志。*/
.tab-button:hover {
background: #e0e0e0;
}
/* 这表示同时具有 tab-button 和 active 样式 */
.tab-button.active {
background: #e0e0e0;
}
.tab {
border: 1px solid #ccc;
padding: 10px;
}
</style>
index.vue
<template>
<div class="demo">
<!-- class 表示按钮 tab-button 样式是一定有的,active 样式有没有则取决于 currentTab是否等于tab-->
<button
v-for="tab in tabs"
:key="tab"
:class="['tab-button',{ active:currentTab == tab}]"
@click="currentTab = tab"
>
{{tab}}
</button>
<!-- currentTab 改变时组件也改变 -->
<component :is="currentTab" class="tab"></component>
</div>
</template>
<script>
import Home from './Home.vue';
import Posts from './Posts.vue';
import Archive from './Archive.vue';
export default {
components: {
Home,
Posts,
Archive
},
data() {
return {
currentTab:'Home',
tabs: ['Home','Posts', 'Archive']
}
}
}
</script>
<style>
</style>
在上面的例子中,被传给 :is 的值可以是,被注册的组件名,或者导入的组件对象。
当使用 <component :is="..."> 来在多个组件间作切换时,被切换掉的组件会被卸载。我们可以通过 <KeepAlive> 组件强制被切换掉的组件仍然保持存活的状态。
DOM内模板解析
这个至少我们项目中不用,暂时不学