vue3父組件使用ref獲取子組件的屬性和方法
在vue3中父組件訪問子組件中的屬性和方法是需要借助于ref:
1.<script setup> 中定義響應式變量 例如: const demo1 = ref(null)
2.在引入的子組件標簽上綁定ref屬性的值與定義的響應式變量同名( <demo1 ref="demo1"/>)。
父組件代碼如下:
<template> <demo1 ref="demo1"/> <demo2 ref="demo2"/> <demo3 ref="demo3"/> </template> <script setup> import Demo1 from '@/components/demo1.vue' import Demo2 from '@/components/demo2.vue' import Demo3 from '@/components/demo3.vue' import {ref,onMounted} from 'vue' const demo1 = ref(null) const demo2 = ref(null) const demo3 = ref(null) onMounted(()=> { console.log(demo1.value.count,'demo1子組件') console.log(demo2.value?.a,'demo2子組件') console.log(demo3.value.list[0],"demo3子組件") }) </script>
子組件代碼如下:
demo1.vue
<template> <h1>i'm demo1 content{{count}}</h1> </template> <script > import {ref} from 'vue' export default { setup () { const count = ref(999) return { count } } }
此時父組件可以獲取到子組件的count屬性
demo2
<template> <h1>我是demo2</h1> </template> <script setup> import {defineExpose,ref} from 'vue' const a = ref('helloss') </script>
當使用 <script setup>
寫法會導致父組件無法訪問到子組件中的屬性和方法。
使用
<script setup>
的組件,想要讓父組件訪問到它的屬性和方法需要借助與defineExpose
來指定需要暴露給父組件的屬性。
更改后的demo2組件
<template> <h1>我是demo2</h1> </template> <script setup> import {defineExpose,ref} from 'vue' const a = ref('helloss') defineExpose({ a }) </script>
demo3
<template> <h1>我是demo3</h1> </template> <script> export default { data () { return { list:['a','b','c'] } }, methods: { btn () { } } }
這種方式,父組件可以正常獲取到里面的屬性和方法。
到此這篇關于vue3父組件使用ref獲取子組件的屬性和方法的文章就介紹到這了,更多相關vue3 ref取獲取子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- vue父組件中獲取子組件中的數(shù)據(jù)(實例講解)
- vue父組件異步獲取數(shù)據(jù)傳給子組件的方法
- 詳解VUE里子組件如何獲取父組件動態(tài)變化的值
- Vue父組件如何獲取子組件中的變量
- vue 父組件通過$refs獲取子組件的值和方法詳解
- vue.js 子組件無法獲取父組件store值的解決方式
- vue實現(xiàn)父組件獲取子組件的方法或?qū)傩灾翟斀?/a>
- vue子組件如何獲取父組件的內(nèi)容(props屬性)
- vue中實現(xiàn)子組件接收父組件方法并獲取返回值
- vue子組件獲取到它父組件數(shù)據(jù)的4種方法
- VUE父組件異步獲取數(shù)據(jù),子組件接收的值為空的問題
- vue父組件異步如何獲取數(shù)據(jù)傳給子組件
- vue子組件實時獲取父組件的數(shù)據(jù)實現(xiàn)
相關文章
關于Vue3父子組件emit參數(shù)傳遞問題(解決Vue2this.$emit無效問題)
相信很多人在利用事件驅(qū)動向父組件扔東西的時候,發(fā)現(xiàn)原來最常用的this.$emit咋報錯了,竟然用不了了,下面通過本文給大家分享關于Vue3父子組件emit參數(shù)傳遞問題(解決Vue2this.$emit無效問題),需要的朋友可以參考下2022-07-07laravel+vue組合的項目中引入ueditor方式(打包成組件形式)
今天小編就為大家分享一篇laravel+vue組合的項目中引入ueditor方式(打包成組件形式),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11Vue請求JSON Server服務器數(shù)據(jù)的實現(xiàn)方法
這篇文章主要介紹了Vue請求JSON Server服務器數(shù)據(jù)的實現(xiàn)方法,需要的朋友可以參考下2018-11-11Vue.js@2.6.10更新內(nèi)置錯誤處機制Fundebug同步支持相應錯誤監(jiān)控
這篇文章主要介紹了Vue.js@2.6.10更新內(nèi)置錯誤處機制,F(xiàn)undebug同步支持相應錯誤監(jiān)控 ,需要的朋友可以參考下2019-05-05