基于类的 vue 组件的标签名称是什么 [英] What is the tag name of class based vue component

查看:39
本文介绍了基于类的 vue 组件的标签名称是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考下面的链接,我们可以使用TypeScript编写的基于类的vue组件.
使用这些自定义组件的正确方法是什么?

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?

例如,下面的 Es5 代码定义了一个组件,该组件可以在其他组件的模板中使用,例如 </my-component> 因为我们将名称 'my-component' 作为 Vue.component 方法的参数.如何在打字稿中实现这一点?

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-Componentshttps://alligator.io/vuejs/typescript-class-components/

基于类的 Vue 组件可以在其他组件的模板字符串中使用的该组件的标签名称是什么?

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

推荐答案

你仍然可以像往常一样注册组件,就像你没有使用 Typescript 一样:

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

这篇关于基于类的 vue 组件的标签名称是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆