vue-class-component

vue-class-component 是尤大大推出的vue对typescript支持的装饰器(库)vue

vue-class-component强调了几点用法:git

一、methods能够直接声明为类成员方法
二、computed属性能够声明为类属性访问器
三、data数据能够声明为类属性
四、data render 和全部Vue生命周期挂钩也能够直接声明为类成员方法,但不能在实例自己上调用它们。在声明自定义方法时,应避免使用这些保留名称。

使用方法

官网demo

<script>
import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  props: {
    propMessage: String
  }
})
export default class App extends Vue {
  // 初始化数据 data能够声明成类属性形式
  msg = 123

  // 使用props
  helloMsg = 'Hello, ' + this.propMessage

  // 生命周期钩子声明  保留名称
  mounted () {
    this.greet()
  }

  // computed属性能够声明成类方法形式
  get computedMsg () {
    return 'computed ' + this.msg
  }

  // method方法能够声明成类方法形式
  greet () {
    alert('greeting: ' + this.msg)
  }
}
</script>
复制代码

createDecorator

createDecorator能够自定义装饰器,须要接受一个回调函数做为第一个参数,包括如下几个参数github

options:对象参数, key ,paramsIndex
// decorators.js
import { createDecorator } from 'vue-class-component'

export const NoCache = createDecorator((options, key) => {
  // component options should be passed to the callback
  // and update for the options object affect the component
  options.computed[key].cache = false
})
import { NoCache } from './decorators'

@Component
class MyComp extends Vue {
  // computed属性不会再被缓存
  @NoCache
  get random () {
    return Math.random()
  }
}
复制代码

Component.registerHooks

自定义钩子vue-router

// class-component-hooks.js
import Component from 'vue-class-component'

// 注册钩子name
Component.registerHooks([
  'beforeRouteEnter',
  'beforeRouteLeave',
  'beforeRouteUpdate' // for vue-router 2.2+
])
// MyComp.js
import Vue from 'vue'
import Component from 'vue-class-component'

@Component
class MyComp extends Vue {
  beforeRouteEnter (to, from, next) {
    console.log('beforeRouteEnter')
    next() // needs to be called to confirm the navigation
  }

  beforeRouteLeave (to, from, next) {
    console.log('beforeRouteLeave')
    next() // needs to be called to confirm the navigation
  }
}
复制代码

箭头函数

this为undefined, 本来使用箭头函数的this实际上指向的是vue实例, 可是将箭头函数定义为类属性并在其中访问它,则它将不起做用,this指向的是vue实例的代理typescript

@Component
class MyComp extends Vue {
  foo = 123
  bar = () => {
    this.foo = 456
  }
}

复制代码

只要将函数定义为方法,就会自动生成vue实例缓存

@Component
class MyComp extends Vue {
  foo = 123

  bar () {
    // Correctly update the expected property.
    this.foo = 456
  }
}
复制代码

类属性的undefined没有作出处理

对于一些属性的初始值应该用null或者data钩子进行处理bash

@Component
class MyComp extends Vue {
  // 不会进行处理
  foo = undefined

  // 会进行处理
  bar = null

  data () {
    return {
      // 会进行处理
      baz: undefined
    }
  }
}
复制代码
本站公众号
   欢迎关注本站公众号,获取更多信息