6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ZOZOテクノロジーズAdvent Calendar 2018

Day 8

クラススタイルVueコンポーネントの変数初期化を改善する

Last updated at Posted at 2018-12-08

背景

TypeScript+vue-class-component環境でcreatedやmountedなどでstateを初期化する場合、クラスの初期化時に一旦stateにnullなどの値を入れる必要があります(これをしないとstateの変更が監視されません)。この時、本来nullが有り得ない場合でも型定義でnullなどを許容せざるを得ません。これを改善するために、Kotlinのlateinitを参考にしてデコレータを作ってみました。


export const LateInit = createDecorator((options, key) => {
  options.mixins = [
    ...options.mixins || [],
    {
      data(this: Vue) {
        return {
          [key]: null
        }
      }
    }
  ]
}

コンポーネントでは以下のように使います。


export default class SomeComponent extends Vue {
  @Lateinit
  windowWidth!: number

  mounted() {
    this.windowWidth = window.innerWidth
  }
}
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?