vue中的class-based compontent

1,494 阅读1分钟

class-baesd compontent这个是官方的称呼,翻译过来就是基于类的组件。 一直以来组件都是一个对象形式的,下面来认识下基于类的组件吧~

直奔用法

相比于比较常用的export一个对象,类的形式要额外引入两个包: npmvue-property-decorator。 其次我们还要在class定义前面加入@Component修饰器,这样一个简单的class-based组件就完成了。

关于修饰器的用法看这里

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自带的,注意都是大写开头的

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我们下次再讲


参考: