三、過濾器及自定義組件
- 過濾器
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
}
})
- 自定義組件
- 基礎(chǔ)配置
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數(shù)組中枫夺,在組件后面加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
將內(nèi)容變成動態(tài)的文判,可編輯的
在模板的某個塊中加入<slot>
并指定名字过椎,在頁面中直接設(shè)置idv的屬性為slot,就可以動態(tài)修改內(nèi)容戏仓。
<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',
})