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
    }
  }
}
複製代碼