vue的复用性与组合
1、混合
混合 (mixins) 是一种分发 Vue 组件中可复用功能的非常灵活的方式。混合对象可以包含任意组件选项。以组件使用混合对象时,所有混合对象的选项将被混入该组件本身的选项
当组件和混合对象含有同名选项时,这些选项将以恰当的方式混合
mixins: [mixin],
切记混合对象的 钩子将在组件自身钩子 之前 调用
var mixin = {
created: function () {
console.log('混合对象的钩子被调用')
}
}
运行效果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>混合</title>
<script type="text/javascript" src="js/vue.js"></script>
<style>
.kuang{
width: 200px;
height: 100px;
border: 1px solid #ccc;
}
.huaguo{
margin-top: 20px;
background: blue;
width: 80px;
height: 30px;
text-align: center;
line-height: 30px;
}
.huaguo1{
width: 100px;
height: 300px;
margin-top: 10px;
background: darkcyan;
}
</style>
</head>
<body>
<div id="app">
<tk></tk>
<hg></hg>
</div>
<script type="text/x-template" id="tcTpl">
<div>
<input type="button" value="弹出" @click="tog"/>
<div class="kuang" v-show="visible">
我是弹出框
<input type="button" value="X" @click="hide"/>
</div>
</div>
</script>
<script type="text/x-template" id="hgTpl">
<div>
<div class="huaguo" @mouseover="tog" @mouseout="tog">显示更多</div>
<div class="huaguo1" v-show="visible">我是划过隐藏的div</div>
</div>
</script>
<script>
//公共的相同的
var gonggong = {
data:function () {
return {
visible:false
};
} ,
methods:{
tog:function(){
this.visible=!this.visible
},
hide:function(){
this.visible=false
}
}
}
//创建组件
var tankuang = {
template:"#tcTpl",
mixins: [gonggong]
}
//创建组件
var huaguo ={
template:"#hgTpl",
mixins: [gonggong]
}
//初始化根实例
var app = new Vue({
el:"#app",
components:{
'tk':tankuang,
'hg':huaguo,
}
});
</script>
</body>
</html>
2、自定义指令
什么是自定义指令
自己开发的指令就叫自定义指令
怎么自定义定义一个指令
Vue.directive("pined",function(){
})
如果对象值为true的时候我们将其div固定到屏幕上
运行效果

<!DOCTYPE html>
<html lang="en">
<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>自定义指令</title>
<script type="text/javascript" src="js/vue.js"></script>
<style>
#app{
height: 1000px;
}
.aa{
width: 200px;
min-height: 100px;
border: 1px solid #ccc;
background: salmon;
}
</style>
</head>
<body>
<div id="app">
<div class="aa" v-pined="fixed">组件可以扩展 HTML 元素,封装可重用的代码</div>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
我要上去了</br>
</div>
<script>
//创建自定义指令
Vue.directive("pined",function(el,binding){
console.log(el);
console.log(binding);
el.style.position="fixed";
el.style.left="20px";
el.style.top="10px";
})
var app = new Vue({
el:"#app",
data:{
fixed:true
}
});
</script>
</body>
</html>
3、插件
开发插件
var 名字 = {};
名字.install = function (Vue, options) {
}
插件的用法
Vue.use(名字)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。