Vue APIs和特殊属性

267 阅读1分钟

Vue常用指令和APIs

1 全局APIs

1.1 Vue.filter

1.1.1 基本语法

Vue.filter (id=>{string},[definition]=>{Function})
注册或获取全局过滤器

Vue.filter ('my-filter', function (value) { // 注册
  // 返回处理后的值
} )

使用

{{ 原数据 || 过滤器名 }}

1.1.2 局部过滤器

export default {
  // ...
  filter:{
    过滤器名 (要被处理的值) {
      // ...
      return 处理后的结果
    }
  }
}

1.1.3 全局引用封装

举例:封装时间转换器

image.png
新建一个timeConverter.js文件

export const timeConverter = time => {
  const t = new Date(time)
  const diff = Date.now() - t.getTime()

  const year = Math.floor(diff / (1000 * 3600 * 24 * 365))
  if (year) {
    return `${year}年前`
  }
  const month = Math.floor(diff / (1000 * 3600 * 24 * 30))
  if (month) {
    return `${month}月前`
  }
  const day = Math.floor(diff / (1000 * 3600 * 24))
  if (day) {
    return `${day}天前`
  }
  const hour = Math.floor(diff / (1000 * 3600))
  if (hour) {
    return `${hour}小时前`
  }
  const minute = Math.floor(diff / (1000 * 60))
  if (minute) {
    return `${minute}分钟前`
  } else {
    return '刚才'
  }
}

main.js中引用

import {timeConverter} from '@/utils/timeConverter.js'
Vue.filter ('timeConverter',timeConverter)
// 第一个参数指自定义过滤器名,第二个参数指引入的函数

1.1.4 扩展封装 (Vue.use)

Vue.use()的格式

Vue.use(Object)
/**
* 对象中必要有一个install方法,这个install方法,在vue.use()会:
* 1.自动被调用
* 2.会自动传入Vue构造器
* /

最终代码,在timeConverter.js文件中加上

+ export default {
+   install: function(Vue) {
+     // console.log('install',val===Vue)
+     // 补充定义全局过滤器
+     // Vue.filter ('timeConverter',(val)=>{})
+     Vue.filter('timeConverter',timeConverter)
+ }

image.pngmain.js中调用

import TimeConverter from '@/utils/timeConverter.js'
Vue.use(TimeConverter)

1.2 Vue.directive

1.2.1 基本语法

Vue.directive (id=>{string},[definition]=>{Function|Object})
注册或获取全局指令

// 注册
Vue.directive ('my-directive',{
  bind:function () {},
  inserted:function () {},
  update:function () {},
  componentUpdated:function () {},
  unbind:function () {}
  // 这里会将'bind'和'update'调用
  
})

1.2.1 举例:聚焦

// 全局
Vue.directive ('focus', {
  inserted:function (el) {
    // 聚焦元素
    el.focus
  }
})
// 局部
export default {
  // ...
  directives:{
    inserted:function (el) {
    el.focus
    }
  }
}

使用

<input v-focus>

2 特殊属性

2.1 Key

key的主要作用

key 的特殊 attribute 主要用在 Vue 的虚拟 DOM 算法,在新旧 nodes 对比时辨识 VNodes。如果不使用 key,Vue 会使用一种最大限度减少动态元素并且尽可能的尝试就地修改/复用相同类型元素的算法。而使用 key 时,它会基于 key 的变化重新排列元素顺序,并且会移除 key 不存在的元素。

key的值为什么要不同?


有相同父元素的子元素必须有独特的key,重复的key会造成渲染错误

2.2 Ref

ref的作用

父组件中修改子组件的数据

<template>
  <SonComponent ref="son" />
</template>

<script>
  export defalut {
    //...
    通过this.$refs来访问子组件
  }
</script>