What is the tag name of class based vue component

六月ゝ 毕业季﹏ 提交于 2019-12-11 04:13:34

问题


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:


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
  }
})


来源:https://stackoverflow.com/questions/43703180/what-is-the-tag-name-of-class-based-vue-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!