先来看混合 mixins
未操作前
鼠标移到bys上
点击按钮
在这两个组件中,存在着重复的代码,通过mixins 减少代码工作量
html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!-- Vue 混合 mixins -->
<div id="app">
<tooltip></tooltip>
<popup></popup>
</div>
<template id="Popuptemp">
<div>
<button @click="toggle">Popup</button>
<div v-if="visible">
<span @click="hide">关闭</span>
<h4>标题</h4>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore hic maxime excepturi nisi, dolor officia quos soluta et, quod! Exercitationem nostrum quo ut quae, tempora eaque! Repellendus, temporibus vel nisi.
</div>
</div>
</template>
<script src="vue.js"></script>
<script src="main.js"></script>
</body>
</html>
JS
var base={
methods:{
show:function(){
this.visible=true;
},
hide:function(){
this.visible=false;
},
toggle:function(){
this.visible=!this.visible;
},
},
data:function(){
return {
visible:false,
}
}
}
Vue.component('tooltip',{
template:'<div><span @mouseenter="show" @mouseleave="hide">bys</span><div v-if="visible">白岩松</div></div>',
mixins:[base],
});
Vue.component('popup',{
template:'#Popuptemp',
mixins:[base],
//设置默认属性,会覆盖mixins中的默认属性
data:function(){
return {
visible:false,
}
}
});
new Vue({
el:'#app',
data:{
}
})
再来看插槽slots
效果图 文字通过html自定义显示
HTML
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.panel {
max-width:300px;
border:1px solid #999;
margin-bottom:15px;
}
.panel > * {
padding:15px;
}
.panel .title{
border-bottom:1px solid #999;
}
.panel .footer{
border-top:1px solid #999;
}
</style>
</head>
<body>
<!-- Vue 插槽slots-->
<div id="app">
<panel>
<div slot="title">我第一帅</div>
<div slot="content">hahahahaha</div>
<div slot="footer">我滴脚</div>
</panel>
<panel>
<div slot="title">我第一帅</div>
<div slot="content">hahahahaha</div>
</panel>
</div>
<template id="panel-tpl">
<div class="panel">
<div class="title">
<slot name="title"></slot>
</div>
<div class="content">
<slot name="content"></slot>
</div>
<div class="footer">
<slot name="footer">默认页脚</slot>
</div>
</div>
</template>
<script src="vue.js"></script>
<script src="main.js"></script>
</body>
</html>
JS
Vue.component('panel',{
template:'#panel-tpl',
})
new Vue({
el:'#app',
data:{}
})