<h3>前言</h3>
會有這一篇是因為以往自己在看Vue的文件會習慣用繁體中文來看,反而忽略掉繁體中文版本的更新可能會比較慢這件事,所以這次就是來記錄哪些我漏掉的東西。
<h4>
computed獲取上一個值 3.4+
</h4>
count不符合條件時,會回傳上一個滿足條件值。
```
<script setup>
import { ref, computed } from 'vue'
const count = ref(2)
const alwaysSmall = computed((previous) => {
if (count.value <= 3) {
return count.value
}
return previous
})
</script>
```
<h4>
onWatcherCleanup 3.5+
</h4>
onWatcherCleanup的功能是清除副作用,不能在非同步的await之後使用,但也有另外的方法可以使用,就是在第三個參數使用onCleanup,也可以達到清除副作用的效果。
而這兩個的差別,看了一下[這篇](https://codlin.me/blog-vue/vue-3-5-update-on-watcher-cleanup-with-the-forgotten-on-cleanup?fbclid=IwY2xjawOkw3pleHRuA2FlbQIxMQBicmlkETFiTjJoV01zVHM0YnRkUTZjc3J0YwZhcHBfaWQQMjIyMDM5MTc4ODIwMDg5MgABHjBbFl1PYvQBjpawWFDfYBg6WgADcSjiy2lq6t1i7_PdpGtsd83-RgcmsXh7_aem_HJS1uBquHRFVAH_17aiX-g),onWatcherCleanup好像是比較適合使用在composable?
只是我自己也不太確定,總之先記錄下來。
```
import { watch, onWatcherCleanup } from 'vue'
watch(id, (newId) => {
const controller = new AbortController()
fetch(`/api/${newId}`, { signal: controller.signal }).then(() => {
// 回調邏輯
})
onWatcherCleanup(() => {
// 終止過期請求
controller.abort()
})
})
---------------------------------------------------------------------------
watch(id, (newId, oldId, onCleanup) => {
// ...
onCleanup(() => {
// 清理邏輯
})
})
watchEffect((onCleanup) => {
// ...
onCleanup(() => {
// 清理邏輯
})
})
```
<h4>
useTemplateRef() 3.5+
</h4>
3.5之前都是使用ref,在3.5之後可以用useTemplateRef(),這也提升了可讀性,如果有要搭配
v-for的話,也是同樣的用法。
```
<script setup>
import { ref, onMounted } from 'vue'
import Child from './Child.vue'
const child = ref(null)
onMounted(() => {
// child.value 是 <Child /> 組件的實例
})
</script>
<template>
<Child ref="child" />
</template>
-------------------------------------------------------------
<script setup>
import { useTemplateRef, onMounted } from 'vue'
// 第一個參數必須與template的ref相同
const input = useTemplateRef('my-input')
onMounted(() => {
input.value.focus()
})
</script>
<template>
<input ref="my-input" />
</template>
```
<h4>
響應式props解構 3.5+
</h4>
在3.4之前,解構出來的foo就不會改變,從3.5開始之後就等值於props.foo,也就是解構出來後也保有響應。
```
const { foo } = defineProps(['foo'])
watchEffect(() => {
console.log(foo)
})
```
3.5之後可以使用JS的語法聲明來幫props設定默認值。
`const { foo = 'hello' } = defineProps<{ foo?: string }>()`
<h4>
延遲解析的 Teleport 3.5+
</h4>
現在可以使用defer來延遲Teleport,也就是會在該目標模板解析完成後,再解析Teleport。
```
<Teleport defer to="#late-div">...</Teleport>
```
<h3>
結語
</h3>
其實除了這些之外,還有其他一些新東西,但是我覺得我暫時可能不會碰到,所以就沒放進來了,另外這邊講的可能比較簡略,如果想要看更詳細的說明可以直接到Vue的文件去看,可能會比較清楚。