[Vue3全面测试] provide及inject的使用

Child.vue:

<template>
    <div>Child Info:{{message}}</div>
</template>
<script>
import {inject,ref,onMounted} from 'vue'
export default {
    name:'Child',
    setup() {
        const message=inject("k1",ref('gCode 打遍天下无敌手.'))
        const hello=inject("k2")
        onMounted(() => {
            hello("gCode Teacher Ok.")
        })
        return {
            message
        }        
    }
}
</script>

Parent.vue:

<template>
<div v-on:click="fn">
    <p>Parent Info:{{msg}}</p>
    <child/>
</div>  
</template>
<script>
import {provide,ref} from 'vue'
import Child from './Child.vue'
export default {   
    name:'Parent',
    components: { Child }, 
    setup() {
        const msg=ref('Exesoft.cn')
        const sayHi=function(name){
            console.log("hello,"+name)
        }
        const fn= function(){
            msg.value= msg.value + " gCode"
        }
        provide("k1",msg)
        provide("k2",sayHi)       
        return {
            msg,
            fn
        }   
    }
}
</script>

 

posted @ 2021-09-24 23:38  dshow  阅读(119)  评论(0编辑  收藏  举报