[TOC]
## 1.过滤器 filter
> 过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符号指示
> 过滤器函数总接收表达式的值 (之前的操作链的结果) 作为第一个参数。在给函数添加参数时,会默认往后排
全局过滤器:
~~~
Vue.filter('filterName', function (value) {
console.log(value);
})
new Vue({
// ...
})
~~~
组件过滤器:
~~~
filters: {
filterName: function (value) {
console.log(value);
}
}
~~~
eg:
~~~
<template>
<div>
<input type="text" v-model="lenth">mm
{{ lenth | meter('mX') }}
</div>
</template>
<script>
export default {
name: "FilterTest",
props: {},
data() {
return {
lenth: 1
};
},
filters: {
meter: function(val, unit) {
val = val || 0;
unit = unit || "m";
return (val / 1000).toFixed(2) + unit;
}
}
};
</script>
<style></style>
~~~
## 2.自定义指令
如果说组件时游戏中的英雄,那么指令就像是英雄的技能,而英雄的技能是可以相似的
在本例中可以看到自定义组件pin的参数binding 在控制台的内容大致是这样的:
~~~
{
arg: " true",
def: {},
expression: " ",
modifiers: {bottom: true,left: true},
name: " ",
rawName: " ",
value: false
}
~~~
~~~
<template>
<div>
<div v-pin:true.bottom.left="card.pinned" class="pinned">
<button @click="card.pinned =! card.pinned">钉起来/取消</button>哇哦,短剑重铸之日,骑士归来之时
</div>
</div>
</template>
<script>
export default {
name: 'dirTest',
data(){
return {
card: {pinned: false}
};
},
props:{},
methods:{},
directives: {
pin: function(element,binding){
console.log(element)
console.log(binding)
var pinned = binding.value;
var position = binding.modifiers;
var warning = binding.arg;
if(pinned) {
element.style.position = 'fixed';
for(var key in position) {
if(position[key]) {
element.style[key] = '10px'
}
}
if(warning === 'true') {
element.style.backgroundColor = '#ff2d51';
}
} else {
element.style.position = 'static'
}
}
}
}
</script>
<style>
.pinned{
padding: 10px;
background: #fafafa;
border-radius: 5px;
}
</style>
~~~