Asked By: Anonymous
I’m just wondering which way is the most reliable to define properties, which should generate an output in the template.
Define property in constructor:
Template reference:
<h1>{{msg}}</h1>
Property definition:
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
@Component
export default class Test extends Vue {
protected msg: string;
public constructor() {
super();
this.msg = 'Today's date ' + moment().format('YYYY/MM/DD');
}
}
</script>
Output in Browser:
<h1>Today's date 2019/03/07</h1>
Define property in mounted lifecycle:
Template reference:
<h1>{{msg}}</h1>
Property definition:
export default class Test extends Vue {
protected msg: string = '';
mounted() {
this.msg = 'Today's date ' + moment().format('YYYY/MM/DD');
}
}
Output in Browser:
<h1>Today's date 2019/03/07</h1>
Define property by get and set, set value in constructor:
Template reference:
<h1>{{msgText}}</h1>
Property definition:
export default class Test extends Vue {
protected msg: string = '';
public constructor() {
super();
this.msgText = 'Today's date ' + moment().format('YYYY/MM/DD');
}
get msgText(): string {
return this.msg;
}
set msgText(msg:string) {
this.msg = msg;
}
}
Output in Browser:
<h1>Today's date 2019/03/07</h1>
Questions:
- All three ways results in the same output. Is there a golden rule / best practice, how properties should be defined and in which lifecycle?
- Is there a difference, if properties are defined in constructor or in mounted lifecycle?
Solution
Answered By: Anonymous
The second approach of using mounted
is preferred over the rest of the approaches. The only change I would suggest is the use of created
hook instead of mounted
:
export default class Test extends Vue {
protected msg: string = '';
created() {
this.msg = 'Today's date ' + moment().format('YYYY/MM/DD');
}
}
Generally, for simple properties, you can directly assign a value at a time of declaration. Use created when your assignment is not simple.
Also, we don’t really use constructors when writing the class-based component. The reason behind is that essentially Vue.js components are object-based. The @Component
decorator is eventually making the component behave like object-based.
Further, if you look at Vue.js component lifecycle methods, then there is no place for a constructor. The initial methods are beforeCreate
-> data
-> created
-> mounted
and so on. How can a beforeCreate execute without an actual call to the constructor? That make is really weird to reason about.
Note 1: For version 3 of Vue.js, official class-based components are
proposed. Thus, this might change in the near future.
Note 2: TypeScript will move msg
declaration to the constructor after compilation and Vue.js seems to work well with it. But it is still unspecified and better be avoided.