Track property in vue component
1 answer
There are several ways to do this. You can set the property on the parent when the asynchronous activity has completed.
console.clear()
Vue.component("child", {
props: ["parentLoading"],
template: `
<h1 v-if="isParentLoading">Parent is loading...</h1>
<h1 v-else>Parent loading complete!</h1>
`,
computed: {
isParentLoading() {
return this.parentLoading
}
}
})
new Vue({
el: "#app",
data: {
loading: true
},
mounted() {
setTimeout(() => this.loading = false, 2000)
}
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<child :parent-loading="loading"></child>
</div>
You can call the method on the child.
console.clear()
Vue.component("child",{
template:`
<h1 v-if="!loaded">Parent is loading...</h1>
<h1 v-else>Parent loading complete!</h1>
`,
data(){
return {
loaded: false
}
},
methods:{
onLoaded(){
this.loaded = true
}
}
})
new Vue({
el:"#app",
mounted(){
setTimeout(() => this.$refs.child.onLoaded(), 2000)
}
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<child ref="child"></child>
</div>
You can just look at the property.
console.clear()
Vue.component("child", {
props: ["parentLoading"],
template: `
<h1 v-if="parentLoading">Parent is loading...</h1>
<h1 v-else>Parent loading complete!</h1>
`,
watch: {
parentLoading(newVal) {
return newVal
}
}
})
new Vue({
el: "#app",
data: {
loading: true
},
mounted() {
setTimeout(() => this.loading = false, 2000)
}
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<child :parent-loading="loading"></child>
</div>
+2
source to share