Understanding Vue.js Decorators
Index:
- 1. @Component Decorator
- 2. @Prop Decorator
- 3. @Watch Decorator
- 4. @Emit Decorator
- 5. @Inject Decorator
- 6. @Provide Decorator
- 7. @Ref Decorator
1. @Component Decorator
The @Component decorator is used to define a Vue component class. It is a fundamental decorator that
sets up the component for use with Vue.
import Vue from 'vue';
import Component from 'vue-class-component';
@Component
export default class MyComponent extends Vue {
// Component logic here
}
2. @Prop Decorator
The @Prop decorator is used to define props for a component. It specifies the type of the prop and
whether it's required.
import { Vue, Component, Prop } from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue {
@Prop(String) readonly propValue!: string;
}
3. @Watch Decorator
The @Watch decorator is used to watch a property for changes and execute a method when the property
changes.
import { Vue, Component, Watch } from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue {
message: string = '';
@Watch('message')
onMessageChanged(newValue: string, oldValue: string) {
// Handle the change
}
}
4. @Emit Decorator
The @Emit decorator is used to emit custom events from a method in a component. It simplifies the
process of emitting events.
import { Vue, Component, Emit } from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue {
@Emit()
sendEvent(data: any) {
// This method emits a custom event
return data;
}
}
5. @Inject Decorator
The @Inject decorator is used to inject a property or service from a parent component. It allows
child components to access properties or services from their parent.
import { Vue, Component, Inject } from 'vue-property-decorator';
@Component
export default class ChildComponent extends Vue {
@Inject() parentProperty!: string;
}
6. @Provide Decorator
The @Provide decorator is used to provide properties or services to child components. It allows a
parent component to share data or services with its children.
import { Vue, Component, Provide } from 'vue-property-decorator';
@Component
export default class ParentComponent extends Vue {
@Provide() sharedData: string = 'Shared data from parent';
}
7. @Ref Decorator
The @Ref decorator is used to get a reference to a child component or DOM element. It simplifies
accessing child components or elements within templates.
import { Vue, Component, Ref } from 'vue-property-decorator';
@Component
export default class ParentComponent extends Vue {
@Ref() childComponent!: MyChildComponent;
}
