provide与inject

main
roger 2 years ago
parent 44e44c3f80
commit aab48951d0
  1. 53
      20_脚手架/vue3_test/src/App.vue
  2. 21
      20_脚手架/vue3_test/src/components/Child.vue
  3. 26
      20_脚手架/vue3_test/src/components/Son.vue

@ -1,44 +1,31 @@
<template>
<input type="text" v-model="keyWord">
<h3>{{keyWord}}</h3>
<div class="app">
<h3>我是app组件{{name}}-{{price}}</h3>
<child/>
</div>
</template>
<script>
import {ref, customRef} from "vue";
import child from "@/components/Child.vue";
import {reactive, toRefs, provide} from "vue";
export default {
name: 'App',
components:{child},
setup() {
// ref
function myRef(value) {
let timer
// console.log('---myRef---', value)
return customRef((track,trigger)=>{
return {
get() {
console.log(`有人从myRef这个容器中读取数据了,我把${value}给他了`)
track() // vue
return value
},
set(newValue) {
console.log(`有人从myRef这个容器中数据改为了:${newValue}`)
clearTimeout(timer)
timer = setTimeout(()=>{
value = newValue
trigger() //vue
}, 500)
}
}
})
}
// let keyWord = ref('hello') // 使ref
let keyWord = myRef('hello')
return {
keyWord,
}
let car = reactive({
name:'奔驰',
price: '40W'
})
provide('car', car) //
return {...toRefs(car)}
}
}
</script>
<style>
.app{
background-color: gray;
padding: 10px;
}
</style>

@ -0,0 +1,21 @@
<template>
<div class="child">
<h3>我是child组件</h3>
<son/>
</div>
</template>
<script>
import son from "@/components/Son.vue";
export default {
name: "Child",
components:{son}
}
</script>
<style>
.child{
background-color: skyblue;
padding: 10px;
}
</style>

@ -0,0 +1,26 @@
<template>
<div class="son">
<h3>我是son组件{{car.name}}-{{car.price}}</h3>
</div>
</template>
<script>
import {inject} from "vue";
export default {
name: "Son",
setup() {
let car = inject('car')
console.log('---son---', car)
return {car}
}
}
</script>
<style scoped>
.son{
background-color: orange;
padding: 10px;
}
</style>
Loading…
Cancel
Save