三、过滤器及自定义组件
- 过滤器
webstorm中,中文字符串显示不出来
<div id="app">
<div>
<input v-model="length"> mm
<br>
{{length | meter}}
</div>
<hr>
<div>
<input v-model="price">
<br>
{{ price | currency('USD') }}
</div>
</div>
<script src="vue.js"></script>
<script>
Vue.filter('meter',function(val,unit){
val = val || 0;
unit = unit || 'm';
return (val / 1000).toFixed(2) + unit;
})
Vue.filter('currency', function (val,unit) {
val = val || 0;
unit = unit || 'yuan';
return val + unit;
});
new Vue({
el: '#app',
data: {
price: 10,
length:0
}
})
- 自定义组件
- 基础配置
vue.directive
- 配置传参和修饰符
<div v-pin:true.bottom.right="card1.pined" class="card">
<button @click = "card1.pined = !card1.pined"/>
i m a</div>
<div v-pin.top.right="card2.pined" class="card">
<a href="#" @click = "card2.pined = !card2.pined" >定住</a>
i m b
</div>
Vue.directive('pin',function (el,binding) {
var pined = binding.value;
var position = binding.modifiers;
var warning=binding.arg;
console.log(pined);
if(pined){
el.style.position = 'fixed';
for(var key in position){
if(position[key]){
el.style[key] = '15px';
}
}
if(warning){
el.style.background = "red";
}
}else {
el.style.position = 'static'
}
})
new Vue({
el: '#app',
data:{
card1:{
pined:false
},
card2:{
pined:false
}
}
})
- 混合mixins
当在不同的组件里使用同一个功能时,为了避免多次封装事件,将通用的事件装进base数组中,在组件后面加mixins:[base]
直接使用。
var base = {
methods: {
show:function(){
this.visible = true
// error:忘加this
},
hide:function(){
this.visible = false
},
toggle:function(){
this.visible = !this.visible
}
},
data: function () {
return{
visible:false
}
},
}
Vue.component('popup',{
template:`
<div>
<span @mouseenter="show" @mouseleave="hide">滑过显示</span>
<div v-if="visible">
嘎嘎嘎嘎嘎
</div>
</div>
`,
mixins:[base]
})
Vue.component('tooltip',{
template:`
<div>
<button @click="toggle">点击显示</button>
<span @click="hide">x</span>
<div v-if="visible">
哈哈啊哈
</div>
</div>
`,
mixins:[base]
})
new Vue({
el: '#app',
})
- 插槽 slots
将内容变成动态的,可编辑的
在模板的某个块中加入<slot>
并指定名字,在页面中直接设置idv的属性为slot,就可以动态修改内容。
<div id="app">
<box>
<div slot="title"> title</div>
<div slot="content"> YYYYYYYY</div>
<div slot="footer">啊啊</div>
</box>
<box><div slot="content"> YYYYYYYY</div></box>
<box><div slot="content"> YYYYYYYY</div></box>
</div>
<template id="box-tpl">
<div class="box">
<div class="title">
<slot name="title"></slot>
</div>
<div class="content">
<slot name="content"></slot>
</div>
<div class="footer">
<slot name="footer">
end
</slot>
</div>
</div>
</template>
Vue.component('box',{
template:'#box-tpl',
})
new Vue({
el: '#app',
})