Skip to content

Instantly share code, notes, and snippets.

@thekhairul
Created March 11, 2021 03:07
Show Gist options
  • Save thekhairul/e13df68e98bf6b5ad85f926ce51d54cb to your computer and use it in GitHub Desktop.
Save thekhairul/e13df68e98bf6b5ad85f926ce51d54cb to your computer and use it in GitHub Desktop.
Vue $watch only once
// Reference: https://stackblitz.com/edit/vue-watch-only-once?file=index.js
import Vue from 'vue';
// Watch "isLive" via $watch to invoke the returned unwatch
// handler after the component went live for the first time.
// Because the websocket stays live and only die visualization
// is stopped.
const Child = Vue.component('child', {
props: {
isLive: {
type: Boolean,
default: false,
}
},
data() {
return {
isWatching: false,
}
},
template: `
<div>
<p>isLive: {{ isLive }}</p>
<p>isWatching: {{ isWatching }}</p>
</div>
`,
created() {
this.isWatching = true;
this.unwatchIsLiveProp = this.$watch('isLive', (newVal) => {
console.log('Watcher was called');
if (newVal) {
this.unwatchIsLiveProp();
this.isWatching = false;
}
});
}
});
new Vue({
el: '#app',
components: {
Child
},
template: `
<div>
<child :isLive="isLive"></child>
<button @click="isLive = !isLive">Go {{ !isLive ? 'Live' : 'Offline' }}</button>
</div>
`,
data() {
return {
isLive: false,
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment