typescript 在Vuejs类组件中声明打字稿接口道具
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50890810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declare typescript interface Props in Vuejs class Component
提问by BrownBe
I'm looking for to declare a typescript interface Props in Vuejs class Component like we can do with React Component.
我正在寻找在 Vuejs 类 Component 中声明一个打字稿接口道具,就像我们可以用 React Component 做的那样。
It's look like this :
它看起来像这样:
import {Component, Prop, Vue} from 'vue-property-decorator'
export class Props extends Vue
{
classElement :string
}
@Component
export default class Menu extends Vue<Props>
{
public props :Props;
constructor(props)
{
super(props);
console.log(props); // return undefined
}
mounted()
{
console.log(this.props.classElement); // return undefined
}
}
Is there a way to achieve this?
有没有办法实现这一目标?
回答by Luis David
Now you can use {type: Object as () => User}
inside a Prop()decorator like this:
现在你可以像这样{type: Object as () => User}
在 Prop()装饰器中使用:
import Vue from 'vue'
import { Component, Prop } from 'vue-property-decorator'
import User from './models/user';
@Component()
export default class Menu extends Vue
{
@Prop({type: Object as () => User})
public user!: User // notice the bang saying to compiler not to warn about no initial value
mounted(){
console.log(this.user);
}
}
回答by Philip Feldmann
Yes, all functionality of the basic javascript vue library can be used when using typescript. I suggest you use the offical class decorator.
是的,使用 typescript 时可以使用基本 javascript vue 库的所有功能。我建议你使用官方的类装饰器。
Defining a prop can be done by simply adding it as a parameter to your class decorator like so:
定义一个 prop 可以通过简单地将它作为参数添加到你的类装饰器中来完成,如下所示:
@Component({
props: {
classElement: String
}
})
export default class Menu extends Vue
{
mounted()
{
console.log(this.classElement);
}
}
Because component accepts an object you can define an interface for this object and pass this in instead as well.
因为组件接受一个对象,所以您可以为该对象定义一个接口,并将其传入。
Alternatively you can use the vue-property-decoratorfor a more angular-like syntax.
或者,您可以使用vue-property-decorator来获得更类似角度的语法。
回答by Navid Mitchell
Additionally it is now possible using the Typescript type PropType.
此外,现在可以使用 Typescript 类型 PropType。
import Vue, { PropType } from 'vue'
import { Component, Prop } from 'vue-property-decorator'
import User from './models/user';
@Component()
export default class Menu extends Vue {
@Prop({type: Object as PropType<User>})
public user!: User // notice the bang saying to compiler not to warn about no initial value
mounted(){
console.log(this.user);
}
}