vue中的class-based compontent

class-baesd compontent這個是官方的稱呼,翻譯過來就是基於類的組件。 一直以來組件都是一個對象形式的,下面來認識下基於類的組件吧~vue

直奔用法

相比於比較經常使用的export一個對象,類的形式要額外引入兩個包: npmvue-property-decorator。 其次咱們還要在class定義前面加入@Component修飾器,這樣一個簡單的class-based組件就完成了。es6

關於修飾器的用法看這裏typescript

import Vue from 'vue'
import { Component } from 'vue-property-decorator'

@Compontent
export default class Hello extends Vue {
    // data property
    name = 'teal'
    
    // life hook
    mounted() {
        
    }
    // method
    greet() {
        console.log(`hello ${this.name}`)
    }
}
複製代碼

更多組件修飾器的使用

下面兩個是vue-property-decorator自帶的,注意都是大寫開頭的npm

watch/computed

export default class Hello extends Vue {
    // watch的使用
    // 這裏的name屬性默認爲null,故能夠不用定義
    // 第一個參數爲要監聽的屬性名,第二個參數爲監聽配置
    @Watch('name', { immidate: false, deep: true })
    toWatchName(value, oldValue) {
        
    }
    
    // computed的使用
    get computedName() {
        return `computed ${this.name}`
    }
}
複製代碼

自定義的修飾器

// decorates.js

export const log = function (msg) {
  return function (target, key, descriptor) {
    let fn = descriptor.value
    descriptor.value = function () {
      console.log(`${key} calling, log ${msg}`)
      return fn.apply(this, arguments)
    }
    return descriptor
  }   
}
}
複製代碼
import Vue from 'vue'
import { Component } from 'vue-property-decorator'
import { log } from './decorates.js'

@Component
export default class Hello extends Vue {
    @log('extra msg')
    greet() {
        // do stuff
    }
}
複製代碼

還有一個vue-class-component咱們下次再講app


參考:ui

相關文章
相關標籤/搜索