onMounted的用法

时间:2025-04-06 14:31:47
<!DOCTYPE html> <div id="app"> <parent></parent> </div> <script src="/vue@next"></script> <script> const {provide, inject, ref, onMounted} = Vue; const app = Vue.createApp({}); const msgKey = Symbol(); const helloKey = Symbol(); app.component('parent', { setup() { const msg = ref('Java无难事'); const sayHello = function(name) { console.log("Hello, " + name) } provide(msgKey, msg); provide(helloKey, sayHello); return { msg } }, template: '<child/>' }) app.component('child', { setup(){ const message = inject(msgKey, ref('VC++ 深入详解')); const hello = inject(helloKey); onMounted(() => hello('zhangsan')); return { message, name } }, template: `<p>{{ message }}</p> <p>Hello, {{ name }} </p>` }) const vm = app.mount('#app') </script> </html>