1.訪問模板引用
要在組合式 API 中獲取引用,我們可以使用輔助函數?useTemplateRef()?
只可以在組件掛載后才能訪問模板引用
<script setup>
import { useTemplateRef, onMounted } from 'vue'// 第一個參數必須與模板中的 ref 值匹配
const input = useTemplateRef('my-input')onMounted(() => {input.value.focus()
})
</script><template><input ref="my-input" />
</template>
2.?v-for
?中的模板引用
當在?v-for
?中使用模板引用時,對應的 ref 中包含的值是一個數組,它將在元素被掛載后包含對應整個列表的所有元素
但是ref 數組并不保證與源數組相同的順序
<script setup>
import { ref, useTemplateRef, onMounted } from 'vue'const list = ref([/* ... */
])const itemRefs = useTemplateRef('items')onMounted(() => console.log(itemRefs.value))
</script><template><ul><li v-for="item in list" ref="items">{{ item }}</li></ul>
</template>
3.組件上的 ref
<script setup>
import { useTemplateRef, onMounted } from 'vue'
import Child from './Child.vue'const childRef = useTemplateRef('child')onMounted(() => {// childRef.value 將持有 <Child /> 的實例
})
</script><template><Child ref="child" />
</template>
注意:
(1)如果是選項式API或沒有使用?<script setup>,
父組件對子組件的每一個屬性和方法都有完全的訪問權.
(2)但是使用了?<script setup>
?的組件是默認私有的,也就是父組件無法訪問子組件上的任何東西,需要添加defineExpose
?宏顯式暴露
<script setup>
import { ref } from 'vue'const a = 1
const b = ref(2)// 像 defineExpose 這樣的編譯器宏不需要導入
defineExpose({a,b
})
</script>