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>
原文:https://www.cnblogs.com/dshow/p/15333104.html