開始使用Vue 3時應避免的十個錯誤
Vue 3 穩(wěn)定已經有一段時間了。許多代碼庫正在生產中使用它,其他人最終也必須進行遷移。我有機會與它一起工作,并記錄了我的錯誤,這可能是你想避免的。
1.使用響應式助手聲明基本類型
數(shù)據(jù)聲明曾經很簡單,但現(xiàn)在有多個輔助工具可用?,F(xiàn)在的一般規(guī)則是:
- 使用 reactive 代替 Object, Array, Map, Set
- 使用 ref 代替 String, Number, Boolean
對于原始值使用響應式會導致警告,并且該值不會被設置為響應式:
/* DOES NOT WORK AS EXPECTED */
<script setup>
import { reactive } from "vue";
const count = reactive(0);
</script>
[Vue warn]: value cannot be made reactive
事例:https://codesandbox.io/s/jolly-ishizaka-ud946f?file=/src/App.vue
矛盾的是,反過來卻行得通!例如,使用 ref 聲明 Array 將在內部調用 reactive 。
2.解構失去響應式值
讓我們想象一下,有一個具有計數(shù)器和一個按鈕以增加計數(shù)器的響應式對象。
<template>
Counter: {{ state.count }}
<button @click="add">Increase</button>
</template>
<script>
import { reactive } from "vue";
export default {
setup() {
const state = reactive({ count: 0 });
function add() {
state.count++;
}
return {
state,
add,
};
},
};
</script>
這個過程相當直接,也能如預期般工作,但你可能會想利用 JavaScript 的解構特性來進行下面的操作。
/* DOES NOT WORK AS EXPECTED */
<template>
<div>Counter: {{ count }}</div>
<button @click="add">Increase</button>
</template>
<script>
import { reactive } from "vue";
export default {
setup() {
const state = reactive({ count: 0 });
function add() {
state.count++;
}
return {
...state,
add,
};
},
};
</script>
地址:https://codesandbox.io/s/gracious-ritchie-sfpswc?file=/src/App.vue
代碼看起來一樣,根據(jù)我們以前的經驗,應該可以運行,但實際上,Vue 的反應性跟蹤是基于屬性訪問的。這意味著我們不能賦值或解構一個響應性對象,因為與第一個引用的響應性連接會丟失。這是使用 reactive helper 的限制之一。
3.對".value"屬性感到困惑
使用 ref 的怪癖之一可能很難適應。Ref 接受一個值并返回一個響應式對象。該值在對象內部在 .value 屬性下可用。
const count = ref(0)
console.log(count) // { value: 0 }
console.log(count.value) // 0
count.value++
console.log(count.value) // 1
但是在模板中使用時,引用會被解包, .value 不需要。
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">
{{ count }} // no .value needed
</button>
</template>
但請注意!解包(Unwrapping)只能在頂層屬性上有效。下面的代碼片段將產生 [object Object]。
// DON'T DO THIS
<script setup>
import { ref } from 'vue'
const object = { foo: ref(1) }
</script>
<template>
{{ object.foo + 1 }} // [object Object]
</template>
正確使用 ".value" 需要時間。盡管我偶爾會忘記它,但我發(fā)現(xiàn)我自己最初比需要的時候用得更頻繁。
4. Emitted Events
自 Vue 初始版本以來,子組件可以使用 emits 與父組件通信。只需要添加一個自定義監(jiān)聽器來監(jiān)聽事件即可。
this.$emit('my-event')
<my-component @my-event="doSomething" />
現(xiàn)在需要使用 defineEmits 宏來聲明emits。
<script setup>
const emit = defineEmits(['my-event'])
emit('my-event')
</script>
記住的另一件事是,無論是 defineEmits 還是 defineProps (用于聲明props),都不需要導入。當使用 script setup. 時,它們會自動可用。
<script setup>
const props = defineProps({
foo: String
})
const emit = defineEmits(['change', 'delete'])
// setup code
</script>
5.聲明額外選項
有一些 Options API 方法的屬性在 script setup 中不受支持。
- name
- inheritAttrs
- 插件或庫需要的自定義選項
解決方案是在同一組件中定義兩個不同的腳本,如腳本設置RFC中所定義的那樣:
<script>
export default {
name: 'CustomName',
inheritAttrs: false,
customOptions: {}
}
</script>
<script setup>
// script setup logic
</script>
6.使用 Reactivity Transform
響應性轉換是 Vue 3 的一項實驗性但有爭議的特性,其目標是簡化聲明組件的方式。這個想法是利用編譯時轉換來自動解包 ref 并使 .value 變得過時。但現(xiàn)在已經被取消,并將在 Vue 3.3 中被移除。它仍然會以一個包的形式存在,但由于它不是 Vue 核心的一部分,所以最好不要在它上面投入時間。
7. 定義異步組件
異步組件以前是通過將它們包含在一個函數(shù)中來聲明的。
const asyncModal = () => import('./Modal.vue')
自 Vue 3 開始,異步組件需要使用 defineAsyncComponent 輔助函數(shù)進行顯式定義:
import { defineAsyncComponent } from 'vue'
const asyncModal = defineAsyncComponent(() => import('./Modal.vue'))
8. 在模板中使用不必要的包裝器
在Vue 2中,組件模板需要一個單一的根元素,這有時會引入不必要的包裝器:
<!-- Layout.vue -->
<template>
<div>
<header>...</header>
<main>...</main>
<footer>...</footer>
</div>
</template>
這不再是問題,因為現(xiàn)在支持多個根元素。??
<!-- Layout.vue -->
<template>
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
</template>
9. 使用錯誤的生命周期事件。
所有組件生命周期事件都被重命名,要么通過添加 on 前綴,要么完全更改名稱??梢栽谝韵聢D形中檢查所有更改。
10. Skipping the Documentation
最后,官方文檔已經進行了重大改版,以反映新的 API,并包含許多有價值的注解、指南和最佳實踐。即使你是一名經驗豐富的 Vue 2 工程師,通過閱讀這個文檔,你肯定能學到一些新的東西。
每個框架都有一個學習曲線,Vue 3的曲線無疑比Vue 2更陡峭。我仍然不確定版本之間的遷移工作是否值得,但組合API更加清晰,一旦掌握了它,就會感覺很自然。