Skip to content

Class API #4

Closed
Closed
@yyx990803

Description

@yyx990803

This is a reference of the current implemented version and open to discussion.

Update: don't know since when but latest Chrome Canary now enables class fields by default, so we can already play with the following API without a transpiler.

Plain ES usage:

import { h, Component } from '@vue/renderer-dom'

class App extends Component {
  static props = {
    msg: String
  }

  // data
  count = 0

  // lifecycle
  created() {
    console.log(this.count)
  }

  // getters are converted to computed properties
  get plusOne() {
    return this.count + 1
  }
  
  // a method
  increment() {
    this.count++
  }

  render(props) {
    return h('div', [
      h('span', this.count),
      h('span', props.msg,
      h('button', {
        // methods are auto-bound when they are accessed via the render proxy
        onClick: this.increment
      }, 'increment')
    ])
  }
}

TS Usage:

import { h, Component, ComponentWatchOptions } from '@vue/renderer-dom'

interface Props {
  msg: string
}

interface Data {
  count: number
}

class App extends Component<Props, Data> {
  static props = {
    msg: String
  }
  
  // data fields
  count: number = 0

  // ComponentWatchOptions type is only needed if `this` inference
  // is needed inside options, e.g. in watch callbacks
  static watch: ComponentWatchOptions<App> {
    count(value) {
      console.log(value)
    }
  }

  created() {
    console.log(this.count)
  }

  get plusOne() {
    return this.count + 1
  }

  increment() {
    this.count++
  }

  render(props) {
    // ...
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions