所有似乎解決類似問題的答案都與 Vue 2 相關,或者根本沒有給出預期的結果。即使檔案中描述的內容也不起作用,因為如果我記錄 ref 的值,我只會看到一個空物件。
我有一個這樣的模板:
<template>
<post-content v-for="post in posts" :post-data="post" :key="post.id" ref="lastPost" />
</template>
PostContent 組件的內容并不重要,把它想象成一個 div 顯示任何內容post.content。
在我posts從 API獲取的腳本中,我希望在參考中包含最后加載的帖子lastPost,以便我可以訪問它HTMLElement(我需要它來處理東西,但在這里我只是嘗試記錄它)。
// This uses composition API with <script setup> syntax
const posts = ref<{id: number, content: string}[]>([])
getPostsFromApi()
.then((thePost: {id: number, content: string}) => posts.value.push(thePost))
const lastPost = ref<typeof PostContent>()
watch(lastPost, () => nextTick(() => console.log(lastPost.value)), {flush: "post"})
但是,這會導致日志成為一個簡單的空物件{}。
- 加載后,我需要能夠訪問 HTMLElement 本身。
- 我需要查看更改的參考,以便每次添加帖子時都可以獲取元素。
- 我只需要在任何給定時間的最后一個帖子,我不在乎以前的帖子。我一次只會添加一個帖子。這就是為什么我不使用陣列作為參考。
為什么記錄空物件而不是根據檔案應該預期的內容?我究竟做錯了什么?
uj5u.com熱心網友回復:
與具有常規<script>塊的SFC 不同,默認情況下<script setup>組件是關閉的——即,<script setup>作用域內的變數不會暴露給父級,除非通過defineExpose(). 記錄的模板 ref 中的空物件意味著您沒有公開任何屬性。
要公開 的根元素PostContent,請在組件中使用模板參考,并使用以下內容公開ref(例如,名為“ $el”)defineExpose():
// PostContent.vue
<script setup lang="ts">
const $el = ref()
defineExpose({ $el })
</script>
<template>
<div ref="$el">...</div>
</template>
順便說一句,watch()with{ flush: 'post' }可以簡化為watchPostEffect():
watch(lastPost, () => nextTick(() => console.log(lastPost.value.$el)), {flush: "post"})
// OR more simply:
watchPostEffect(() => console.log(lastPost.value.$el))
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344823.html
標籤:打字稿 Vue.js Vuejs3 vue-composition-api
上一篇:我想隱藏我的API密鑰,但我想在同一時間使用GitHub上頁部署這些鍵
下一篇:Vue.js不呈現串列中的元素
