I recently entered the Vueverse (using Vue.js 2) and I'm encountering some challenges with the watch
feature. When the component is mounted
, I fetch data from an API and use it to set the value of a radio button. Essentially, I have two radio buttons with values of 1
and 0
(true/false).
The watcher seems to be functioning correctly as it triggers when the value changes. However, I don't want it to trigger on the initial change - that's when I first set the value from the backend.
I've experimented with different lifecycle hooks like beforeCreated
, created
, and so forth, but it always triggers.
It's likely something simple to do, but I can't seem to figure it out and haven't found relevant information online (possibly using the wrong search terms).
Here's the code snippet:
import axios from "axios";
export default {
name: 'Settings',
data: () => ({
/* initialize motionSensor as null */
motionSensor: null
}),
mounted() {
/* Fetch initial value from the backend, which unintentionally triggers the watcher */
axios
.get('http://localhost:8000/status.json')
.then(response => {
response.data['motionsensor'] ? this.motionSensor = "1" : this.motionSensor = "0";
})
},
watch: {
motionSensor: function(val) {
alert('Motion sensor value is now: ' + val)
}
}
}