I have a vue component below that I want to watch to trigger on when it's getting mounted. How do I do that?
Vue.component('check-mark', {
name: 'check-mark',
template: `<input :value="value"/>`,
props: {
value: {
type: String,
required: true,
},
},
mounted: async function () {
//trigger this.value watch() here
},
watch: {
value: function (value) {
if (value == 'Y') {
this.class = 'checked';
} else {
this.class = 'unchecked';
}
},
},
});
I think you might be better served by a computed in this case.
computed:{
class(){
return this.value === 'Y' ? 'checked' : 'unchecked'
}
}
But if you really want to use a watcher, abstract the code you do in the watch into a method and call it from mounted.
Vue.component('check-mark', {
name: 'check-mark',
template: `
<input :value="value">
`,
props: {
value: {
type: String,
required: true,
},
},
data(){
return {
class: null
}
},
methods:{
setClass(value){
if (value == 'Y') {
this.class = 'checked';
} else {
this.class = 'unchecked';
}
}
},
mounted: function () {
this.setClass(this.value)
},
watch: {
value: function (value) {
this.setClass(value)
},
},
});