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取獲取子組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于Vue3父子組件emit參數傳遞問題(解決Vue2this.$emit無效問題)
相信很多人在利用事件驅動向父組件扔東西的時候,發(fā)現原來最常用的this.$emit咋報錯了,竟然用不了了,下面通過本文給大家分享關于Vue3父子組件emit參數傳遞問題(解決Vue2this.$emit無效問題),需要的朋友可以參考下2022-07-07
laravel+vue組合的項目中引入ueditor方式(打包成組件形式)
今天小編就為大家分享一篇laravel+vue組合的項目中引入ueditor方式(打包成組件形式),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Vue.js@2.6.10更新內置錯誤處機制Fundebug同步支持相應錯誤監(jiān)控
這篇文章主要介紹了Vue.js@2.6.10更新內置錯誤處機制,Fundebug同步支持相應錯誤監(jiān)控 ,需要的朋友可以參考下2019-05-05

