Vue 3 父组件 setup 中执行子组件方法
Vue 3 父组件调用子组件方法,可以在生命周期函数中直接调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, minimum-scale=1, user-scalable=no"> <title>父组件调用子组件方法</title> <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.2.37/vue.global.js"></script> </head> <div id="root"></div> <body> </body> <script> const app = Vue.createApp({ template: ` <div> 父页面 <child ref="sonRef"/> <button @click="handleClick">test</button> </div> `, setup() { const { ref, onMounted } = Vue; const sonRef = ref(); const handleClick = () => { sonRef.value.song(); } onMounted(() => { console.log('这里执行子组件方法', sonRef.value.song()); }); return { sonRef, handleClick } } }); app.component('child', { template: ` <div> 子页面 </div> `, setup() { const song = () => alert('hello world'); return { song, } } }); app.mount('#root'); </script> </html> |
微信扫描下方的二维码阅读本文
Chinge_Yang
2022年8月19日 18:03
收藏的代码段多了,自然就成大神了