First, make sure your Vue version supports Provide the following two simple components for binding
1. Parent component.
<template>
<div class="home">
count now is -> {{count}} <button @click="++count"</button> < button@click ="--count"</button> <br><br> <BackupChild/> </div> </template> <script> import BackupChild from'./Backup_child'
export default {
name: 'backup'.data() {return {
count:10
}
},
provide() {let sendCount = {}
Object.defineProperty(sendCount,'count',{
get:()=>this.count
})
return {
sendCount
}
},
methods:{
},
components: {
BackupChild
}
}
</script>
Copy the code
2. The child component
<template>
<div class="home">
i am backup child page count is ->{{sendCount.count}}
</div>
</template>
<script>
export default {
name: 'backupChild',
inject:['sendCount'],
components: {
}
}
</script>
Copy the code
So just a quick word here. The parent controls the value of count by adding one and subtracting one buttons. The parent component is passed to the child component through provide, and the child component inject receives. Note that in passing the value, count is passed through the Object, which, since it is an Object, can be detected using Object.defineProperty. DefineProperty gets triggered when the child component calls, returning the parent count.
Note that get uses the arrow function because of the this scope