我在父组件中有一个异步操作,需要通知子,这个操作已经完成。我可以在孩子看房产改变吗?有点像:
new Vue({
props:['parentReady'],
watch:{
parentReady(val){
alert('parentReady prop was changed');
}
}
})
答案 0 :(得分:7)
有几种方法可以做到这一点。您可以在异步操作完成时在父级中设置属性。
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)
}
})
&#13;
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<child :parent-loading="loading"></child>
</div>
&#13;
你可以给孩子调用一个方法。
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)
}
})
&#13;
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<child ref="child"></child>
</div>
&#13;
您可以观看该属性。
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)
}
})
&#13;
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<child :parent-loading="loading"></child>
</div>
&#13;