What is the tag name of class based vue component

2019-07-25 09:26发布

Refer to the link below, we can use class based vue component which is written in TypeScript.
What is the correct way to use these custom components?

For example, the Es5 code below defines a component which can be used in other components' template like <my-component></my-component> because we put a name 'my-component' as a parameter to Vue.component method. How to achieve this in typescript?

Vue.component('my-component', {
  template: '<span>{{ message }}</span>',
  data: {
    message: 'hello'
  }
})

Vue.component('parent-component', {
  template: '<my-component></my-component>'
})

https://vuejs.org/v2/guide/typescript.html#Class-Style-Vue-Components https://alligator.io/vuejs/typescript-class-components/

Class-Based Vue Component What is the tag name of this component which can be used in other components' template string?

import Vue from 'vue'
import Component from 'vue-class-component'
// The @Component decorator indicates the class is a Vue component
@Component({
  // All component options are allowed in here
  template: '<button @click="onClick">Click!</button>'
})
export default class MyComponent extends Vue {
  // Initial data can be declared as instance properties
  message: string = 'Hello!'
  // Component methods can be declared as instance methods
  onClick (): void {
    window.alert(this.message)
  }
}

1条回答
走好不送
2楼-- · 2019-07-25 09:54

You can still register components like usual as if you weren't using Typescript:

// MyComponent.ts

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  template: '<button @click="onClick">Click!</button>'
})
export default class MyComponent extends Vue {
  message: string = 'Hello!'
  onClick (): void {
    window.alert(this.message)
  }
}

// Register the component globally
Vue.component('my-component', MyComponent)

Since the code above is exporting the component from a module, you probably shouldn't register it globally (unless it is a common component). The best way would be to import the component into the modules of other components which will use it:

// App.ts

import Vue from 'vue'
import MyComponent from './MyComponent'

new Vue({
  el: '#app',
  components: {
    MyComponent  // will register as <my-component> in #app's template
  }
})
查看更多
登录 后发表回答