参考下面的链接,我们可以使用用 TypeScript 编写的基于类的 vue 组件。
使用这些自定义组件的正确方法是什么?
例如,下面的 Es5 代码定义了一个可以在其他组件模板中使用的组件,例如<my-component></my-component>
因为我们写了一个名字'my-component'
作为参数Vue.component
方法。如何在打字稿中实现这一点?
Vue.component('my-component', {
template: '<span>{{ message }}</span>',
data: {
message: 'hello'
}
})
Vue.component('parent-component', {
template: '<my-component></my-component>'
})
https://v2.vuejs.org/v2/guide/typescript.html#Class-Style-Vue-Components https://v2.vuejs.org/v2/guide/typescript.html#Class-Style-Vue-Components
https://alligator.io/vuejs/typescript-class-components/ https://alligator.io/vuejs/typescript-class-components/
基于类的 Vue 组件该组件可以在其他组件的模板字符串中使用的标签名称是什么?
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 一样:
// 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)
由于上面的代码是从模块导出组件,因此您可能不应该全局注册它(除非它是通用组件)。最好的方法是将组件导入到将使用它的其他组件的模块中:
// 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
}
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)