在vue3中父組件訪問子組件中的屬性和方法是需要借助于ref:
1.<script setup> 中定義響應式變量 例如: const demo1 = ref(null)
2.在引入的子組件標簽上綁定ref屬性的值與定義的響應式變量同名( <demo1 ref="demo1"/>)。
父組件代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <template> ?? <h1>i 'm demo1 content{{count}}</h1> </template> <script > import {ref} from ' vue' export default { ???? setup () { ???????? const count = ref(999) ???????? return { ???????????? count ???????? } ???? } } |
此時父組件可以獲取到子組件的count屬性(此時子組件用的是? export default 的寫法)
demo2
1 2 3 4 5 6 7 8 | <template> ?? <h1>我是demo2</h1> </template> <script setup> import {defineExpose,ref} from 'vue' const a = ref( 'helloss' ) </script> |
當使用?<script setup>
?寫法會導致父組件無法訪問到子組件中的屬性和方法。
使用?<script setup>
?的組件,想要讓父組件訪問到它的屬性和方法需要借助與defineExpose
來指定需要暴露給父組件的屬性。
更改后的demo2組件
1 2 3 4 5 6 7 8 9 10 11 | <template> ?? <h1>我是demo2</h1> </template> <script setup> import {defineExpose,ref} from 'vue' const a = ref( 'helloss' ) defineExpose({ ???? a }) </script> |
demo3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <template> ?? <h1>我是demo3</h1> </template> <script> export default { ?? data () { ???? return { ???????? list:[ 'a' , 'b' , 'c' ] ???? } ?? }, ?? methods: { ???? btn () { ???? } ?? } } |
這種方式,父組件可以正常獲取到里面的屬性和方法。