# Vue2

# V指令与事件修饰符

# 1. v指令

指令名 描述 简写
v-bind 绑定属性。
v-on 绑定事件。 @
v-model 数据双向绑定。v-bind与input事件的语法糖。
v-slot 具名插槽,只能在template标签上使用 #
v-cloak 首屏加载出现闪烁,渲染的dom出现闪烁的情况下使用。
v-text 会将text的内容渲染进dom内。 innerText的语法糖。
v-html 可以渲染文本里的元素标签。innerHTML的语法糖。
v-once 添加会后DOM只会渲染一次,变成静态资源。
v-for 渲染数组 v-for=“(item, index) in list” :key="index" 指定key来更好的复用DOM。也可以直接循环数字。
v-show 是否展示DOM。display=none的语法糖。
v-if、v-else-if、v-else 是否展示DOM。每次都会重新渲染DOM。

# 2. 事件修饰符

名称 描述
.stop 阻止事件冒泡。 event.stopPropagation(); event.cancelBubble = true;的语法糖。
.prevent 阻止默认事件。event.preventDefault();event.returnValue = false;的语法糖。
.capture 使用事件捕获模式触发事件。
.self 只在点击当前元素本身触发事件(也不包括当前元素的子元素)。 event.target(触发元素)与event.currentTarget(绑定元素)的语法糖。
.once 事件只会触发一次。

# 3. 键盘修饰符

自定义键盘修饰符

Vue.config.keyCodes.f2 === 133 // keycodes码值

# 自定义指令

# 1. 创建全局自定义指令

interface Binding {
  name: string, // 指令名称
  value: any, // 指令后的值
  expression: string, // 未处理的指令的值 如 1 + 1 value 会处理为2
  modifiers: object // 修饰符。 例:v-sortable.sort。modifiers为{ sort: true }
}

interface Directive {
  // el为当前绑定元素的dom。指令中无法获取实例this。
  // 当指令绑定到元素上的时候 会调用bind
  bind(el: HTMLElement, binding: Binding): void,
  //当元素插入到DOM中,会执行inserted函数
  inserted(el: HTMLElement, binding: Binding): void,
  // 当Vnode更新的时候会执行,可能会触发多次
  updated(el: HTMLElement, binding: Binding): void,
  // 被绑定元素所在模板完成一次更新周期时调用
  componentUpdated(el: HTMLElement, binding: Binding): void,
  // 指令与元素解绑时调用
  unbind(el: HTMLElement, binding: Binding): void
}

Vue.directive(name: string, options: Directive);

# 2. 私有自定义指令

export default {
  // ...
  directives: {
    name: {
      inserted(el, { value }) {
        // doSomething...
      }
    }
  }
}

# 过滤器

  • value: 使用过滤器的源数据
  • arg: 为使用过滤器时自己传的值

# 1. 创建全局过滤器

interface Filters {
  (value: any, ...arg?: any[]): string | number 
}
Vue.filter(name: string, callback: Filters)

# 2. 创建私有过滤器

<template>
  <span>{{ value | formatDate }}</span>
</template>

<script>
export default {
  // ...
  filters: {
    formatDate(date) {
      // doSomething...
    }
  }
}
</script>