函数简写
当想在 bind 和 update 中触发相同行为,而不关心其他钩子时,可以写成函数的形式:
Vue.directive('myshow', (el, binding) => {
const { value } = binding;
const display = value ? '' : 'none';
el.style.display = display;
})
Vue.directive('slice', (el, binding, vnode) => {
const vm = vnode.context;
let { value, expression, arg, modifiers } = binding;
if(modifiers.number) {
value = value.replace(/[^0-9]/g, '');
}
el.value = value.slice(0, arg);
vm[expression] = value.slice(0, arg);
el.oninput = function (e) {
let inputVal = el.value;
if(modifiers.number) {
inputVal = inputVal.replace(/[^0-9]/g, '');
}
el.value = inputVal.slice(0, arg);
vm[expression] = inputVal.slice(0, arg);
}
})
对象字面量
如果自定义指令需要多个值,可以传入一个 JS 对象字面量。指令函数能够接受所有合法的 JS 表达式。
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
Vue.directive('demo', function (el, binding) {
console.log(binding.value.color) // => "white"
console.log(binding.value.text) // => "hello!"
})
过滤器
自定义过滤器,用于一些常见的文本格式化。
过滤器可用在两个地方:双花括号插值 和 v-bind 表达式,添加在JS表达式的尾部,由“管道”符号表示:
<!-- 在双花括号中 -->
{{ message | filter }}
<!-- 在 v-bind 中 -->
<div v-bind:id="id | filter"></div>
定义过滤器
全局过滤器:
Vue.filter('filter', value => {})
局部过滤器:
filter () {
return xxx;
}
参数
当过滤器形式为 msg | filter
时,filter过滤器接收一个参数,参数为msg
。
当过滤器形式为 msg | filter('a')
时,filter过滤器接收两个参数,参数为msg, 'a'
过滤器串联
{{ msg | filterA | filterB }}
在这个例子中,filterA的参数为msg
,filterB的参数为filterA。