当前位置:   article > 正文

vue函数简写,对象字面量和过滤器_vue 函数简写

vue 函数简写

函数简写

当想在 bind 和 update 中触发相同行为,而不关心其他钩子时,可以写成函数的形式:

Vue.directive('myshow', (el, binding) => {
  const { value } = binding;
  const display = value ? '' : 'none';
  el.style.display = display;
})
  • 1
  • 2
  • 3
  • 4
  • 5
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);
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

对象字面量

如果自定义指令需要多个值,可以传入一个 JS 对象字面量。指令函数能够接受所有合法的 JS 表达式。

<div v-demo="{ color: 'white', text: 'hello!' }"></div>
  • 1
Vue.directive('demo', function (el, binding) {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text)  // => "hello!"
})
  • 1
  • 2
  • 3
  • 4

过滤器

自定义过滤器,用于一些常见的文本格式化。

过滤器可用在两个地方:双花括号插值 和 v-bind 表达式,添加在JS表达式的尾部,由“管道”符号表示:

<!-- 在双花括号中 -->
{{ message | filter }}

<!-- 在 v-bind 中 -->
<div v-bind:id="id | filter"></div>
  • 1
  • 2
  • 3
  • 4
  • 5

定义过滤器

全局过滤器:

Vue.filter('filter', value => {})
  • 1

局部过滤器:

filter () {
  return xxx;
}
  • 1
  • 2
  • 3

参数

当过滤器形式为 msg | filter 时,filter过滤器接收一个参数,参数为msg

当过滤器形式为 msg | filter('a')时,filter过滤器接收两个参数,参数为msg, 'a'

过滤器串联

{{ msg | filterA | filterB }}
  • 1

在这个例子中,filterA的参数为msg,filterB的参数为filterA。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/208324
推荐阅读
相关标签
  

闽ICP备14008679号