Vue Trigger watch on mounted
As of Vue 2.0, there is now a way to do it in the watcher itself, using immediate: true
.
There's a minor caveat for when in the lifecycle this runs the watcher, see edit.
Before using this, ensure you really need a watcher rather than a computed property.
There are many advantages to computed properties and more often than not they are the better solution.
This functionality should only be used if computed properties are insufficient.
In the specific case of the original question, a computed property for
class
would definitely be better, but posted this just in case other people stumble across this post with a case where a computed property won't do (as I did).
Watchers can be an object instead of just a function, and take property immediate
that tells vue to run the watcher when the component is created (different from mounted).
The function that is run is then in the handler
property.
So, in your example, your watcher could be:
watch: {
value: {
handler: function(value) {
if (value == 'Y') {
this.class = 'checked';
} else {
this.class = 'unchecked';
}
},
immediate: true
},
}
Edit
It was pointed out in the comments that the immediate
option triggers the watcher when the component is created rather than when mounted. In simple cases, these can be seen as equivalent.
If you really want specifically the run when mounted functionality for a watcher, you could simply have the field you're watching be some dummy value, say null
or undefined
, and then actually initialize it in the mounted()
hook. The above example would become:
data() {
return {
value: undefined
}
},
mounted() {
// Set value to actual initial value,
// which will trigger the watcher
this.value = 'Y';
},
watch: {
value(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)
},
},
});