I'm looking for to declare a typescript interface Props in Vuejs class Component like we can do with 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?
To let Typescript enters into your Vue components, 2 additions are mandatory in each component file: Adding the lang="ts" attribute to the script tag so that Typescript can recognized it.
Vue is written in TypeScript itself and provides first-class TypeScript support. All official Vue packages come with bundled type declarations that should work out-of-the-box.
Now that Vue. js officially supports TypeScript, it's possible to create TypeScript projects from scratch using Vue CLI. However, you still need some third-party packages with custom decorators and features to create a true, complete TypeScript application.
Now you can use {type: Object as () => User}
inside a Prop() decorator like this:
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);
}
}
Additionally it is now possible using the Typescript type 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);
}
}
Yes, all functionality of the basic javascript vue library can be used when using typescript. I suggest you use the offical class decorator.
Defining a prop can be done by simply adding it as a parameter to your class decorator like so:
@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-decorator for a more angular-like syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With