詳解Vue3?父組件調(diào)用子組件方法($refs?在setup()、<script?setup>?中使用)
在 vue2
中 ref
被用來獲取對應(yīng)的子元素,然后調(diào)用子元素內(nèi)部的方法。
<template> <!-- 子組件 --> <TestComponent ref="TestComponent"></TestComponent> </template> <script> // 導(dǎo)入子組件 import TestComponent from './TestComponent' export default { components: { TestComponent }, mounted () { // 調(diào)用子組件方法 this.$refs.TestComponent.show() } } </script>
在 Vue3
setup () {}
中使用 ref
,如何獲取到子元素,并調(diào)用方法:
<template> <!-- 子組件 --> <TestComponent ref="RefTestComponent"></TestComponent> </template> <script> // 導(dǎo)入子組件 import TestComponent from './TestComponent' import { ref } from 'vue' import { nextTick } from 'process' export default { components: { TestComponent }, setup () { // 定義一個對象關(guān)聯(lián)上子組件的 ref 值(注意:這里的屬性名必須跟子組件定義的 ref 值一模一樣,否者會關(guān)聯(lián)失效) const RefTestComponent = ref(null) // 延遲使用,因為還沒有返回跟掛載 nextTick(() => { RefTestComponent.value.show() }) // 返回 return { RefTestComponent } } } </script>
在 Vue3
<script setup>
中使用 ref
,如何獲取到子元素,并調(diào)用方法
<template> <!-- 子組件 --> <TestComponent ref="RefTestComponent"></TestComponent> </template> <script setup> // 導(dǎo)入子組件 import TestComponent from './TestComponent' import { ref } from 'vue' import { nextTick } from 'process' // 定義一個對象關(guān)聯(lián)上子組件的 ref 值(注意:這里的屬性名必須跟子組件定義的 ref 值一模一樣,否者會關(guān)聯(lián)失效) const RefTestComponent = ref(null) // 延遲使用,因為還沒掛載 nextTick(() => { RefTestComponent.value.show() }) </script>
到此這篇關(guān)于Vue3 父組件調(diào)用子組件方法($refs 在setup()、<script setup> 中使用)的文章就介紹到這了,更多相關(guān)Vue3 父組件調(diào)用子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue使用JSEncrypt實現(xiàn)rsa加密及掛載方法
這篇文章主要介紹了Vue使用JSEncrypt實現(xiàn)rsa加密及掛載方法,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02vue實現(xiàn)一個矩形標(biāo)記區(qū)域(rectangle marker)的方法
這篇文章主要介紹了vue實現(xiàn)一個矩形標(biāo)記區(qū)域 rectangle marker的方法,幫助大家實現(xiàn)區(qū)域標(biāo)記功能,感興趣的朋友可以了解下2020-10-10vue后臺項目如何使用router.addRoutes動態(tài)加入路由的思路
這篇文章主要介紹了vue后臺項目如何使用router.addRoutes動態(tài)加入路由的思路,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06vue中provide?inject的響應(yīng)式監(jiān)聽解決方案
這篇文章主要介紹了vue中provide?inject的響應(yīng)式監(jiān)聽解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04vue3 reactive函數(shù)用法實戰(zhàn)教程
reactive是Vue3中提供實現(xiàn)響應(yīng)式數(shù)據(jù)的方法,reactive的用法與ref的用法相似,也是將數(shù)據(jù)變成響應(yīng)式數(shù)據(jù),當(dāng)數(shù)據(jù)發(fā)生變化時UI也會自動更新,這篇文章主要介紹了vue3 reactive函數(shù)用法,需要的朋友可以參考下2022-11-11