五種在 Vue 3 中定義組件的方法
Vue 正在不斷發(fā)展,目前,在Vue 3 中有多種定義組件的方法。從選項(xiàng)到組合再到類(lèi) API,情況大不相同,如果您剛剛開(kāi)始,可能會(huì)感到困惑。讓我們定義一個(gè)簡(jiǎn)單的組件并使用所有可用的方法重構(gòu)它。
1. Options API
這是在 Vue 中聲明組件的最常見(jiàn)方式。從版本 1 開(kāi)始可用,您很可能已經(jīng)熟悉它。一切都在對(duì)象內(nèi)聲明,數(shù)據(jù)在幕后由 Vue 響應(yīng)。它不是那么靈活,因?yàn)樗褂?mixin 來(lái)共享行為。
<script>
import TheComponent from './components/TheComponent.vue'
import componentMixin from './mixins/componentMixin.js'
export default {
name: 'OptionsAPI',
components: {
TheComponent,
AsyncComponent: () => import('./components/AsyncComponent.vue'),
},
mixins: [componentMixin],
props: {
elements: {
type: Array,
},
counter: {
type: Number,
default: 0,
},
},
data() {
return {
object: {
variable: true,
},
}
},
computed: {
isEmpty() {
return this.counter === 0
},
},
watch: {
counter() {
console.log('Counter value changed')
},
},
created() {
console.log('Created hook called')
},
mounted() {
console.log('Mounted hook called')
},
methods: {
getParam(param) {
return param
},
emitEvent() {
this.$emit('event-name')
},
},
}
</script>
<template>
<div class="wrapper">
<TheComponent />
<AsyncComponent v-if="object.variable" />
<div class="static-class-name" :class="{ 'dynamic-class-name': object.variable }">
Dynamic attributes example
</div>
<button @click="emitEvent">Emit event</button>
</div>
</template>
<style lang="scss" scoped>
.wrapper {
font-size: 20px;
}
</style>
2.Composition API
經(jīng)過(guò)多次討論、來(lái)自社區(qū)的反饋,以及令人驚訝的是,在這個(gè) RFC 中,有很多戲劇性的內(nèi)容,在 Vue 3 中引入了 Composition API。 目的是提供更靈活的 API 和更好的 TypeScript 支持。這種方法在很大程度上依賴于設(shè)置生命周期掛鉤。
<script>
import {
ref,
reactive,
defineComponent,
computed,
watch,
} from 'vue'
import useMixin from './mixins/componentMixin.js'
import TheComponent from './components/TheComponent.vue'
export default defineComponent({
name: 'CompositionAPI',
components: {
TheComponent,
AsyncComponent: () => import('./components/AsyncComponent.vue'),
},
props: {
elements: Array,
counter: {
type: Number,
default: 0,
},
},
setup(props, { emit }) {
console.log('Equivalent to created hook')
const enabled = ref(true)
const object = reactive({ variable: false })
const { mixinData, mixinMethod } = useMixin()
const isEmpty = computed(() => {
return props.counter === 0
})
watch(
() => props.counter,
() => {
console.log('Counter value changed')
}
)
function emitEvent() {
emit('event-name')
}
function getParam(param) {
return param
}
return {
object,
getParam,
emitEvent,
isEmpty
}
},
mounted() {
console.log('Mounted hook called')
},
})
</script>
<template>
<div class="wrapper">
<TheComponent />
<AsyncComponent v-if="object.variable" />
<div class="static-class-name" :class="{ 'dynamic-class-name': object.variable }">
Dynamic attributes example
</div>
<button @click="emitEvent">Emit event</button>
</div>
</template>
<style scoped>
.wrapper {
font-size: 20px;
}
</style>
如您所知,使用這種混合方法需要大量樣板代碼,而且設(shè)置函數(shù)很快就會(huì)失控。在遷移到 Vue 3 時(shí),這可能是一個(gè)很好的中間步驟,但是語(yǔ)法糖可以讓一切變得更干凈。
3.Script setup
在 Vue 3.2 中引入了一種更簡(jiǎn)潔的語(yǔ)法。通過(guò)在腳本元素中添加設(shè)置屬性,腳本部分中的所有內(nèi)容都會(huì)自動(dòng)暴露給模板。通過(guò)這種方式可以刪除很多樣板文件。
<script setup>
import {
ref,
reactive,
defineAsyncComponent,
computed,
watch,
onMounted,
} from "vue";
import useMixin from "./mixins/componentMixin.js";
import TheComponent from "./components/TheComponent.vue";
const AsyncComponent = defineAsyncComponent(() =>
import("./components/AsyncComponent.vue")
);
console.log("Equivalent to created hook");
onMounted(() => {
console.log("Mounted hook called");
});
const enabled = ref(true);
const object = reactive({ variable: false });
const props = defineProps({
elements: Array,
counter: {
type: Number,
default: 0,
},
});
const { mixinData, mixinMethod } = useMixin();
const isEmpty = computed(() => {
return props.counter === 0;
});
watch(() => props.counter, () => {
console.log("Counter value changed");
});
const emit = defineEmits(["event-name"]);
function emitEvent() {
emit("event-name");
}
function getParam(param) {
return param;
}
</script>
<script>
export default {
name: "ComponentVue3",
};
</script>
<template>
<div class="wrapper">
<TheComponent />
<AsyncComponent v-if="object.variable" />
<div
class="static-class-name"
:class="{ 'dynamic-class-name': object.variable }"
>
Dynamic attributes example
</div>
<button @click="emitEvent">Emit event</button>
</div>
</template>
<style scoped>
.wrapper {
font-size: 20px;
}
</style>
4. Reactivity Transform
這是非常有爭(zhēng)議的,被刪除了!這使得腳本設(shè)置成為本文的明確答案。(26/1/2023 更新)
以下代碼段中演示的腳本設(shè)置存在問(wèn)題。
<script setup>
import { ref, computed } from 'vue'
const counter = ref(0)
counter.value++
function increase() {
counter.value++
}
const double = computed(() => {
return counter.value * 2
})
</script>
<template>
<div class="wrapper">
<button @click="increase">Increase</button>
{{ counter }}
{{ double }}
</div>
</template>
正如您所注意到的,使用 .value 訪問(wèn)反應(yīng)式計(jì)數(shù)器感覺(jué)不自然,并且是混淆和錯(cuò)誤輸入的常見(jiàn)來(lái)源。
有一個(gè)實(shí)驗(yàn)性解決方案利用編譯時(shí)轉(zhuǎn)換來(lái)解決此問(wèn)題。反應(yīng)性轉(zhuǎn)換是一個(gè)可選的內(nèi)置步驟,它會(huì)自動(dòng)添加此后綴并使代碼看起來(lái)更清晰。
<scr
ipt setup>
import { computed } from 'vue'
let counter = $ref(0)
counter++
function increase() {
counter++
}
const double = computed(() => {
return counter * 2
})
</script>
<template>
<div class="wrapper">
<button @click="increase">Increase</button>
{{ counter }}
{{ double }}
</div>
</template>
$ref 需要一個(gè)構(gòu)建步驟,但在訪問(wèn)變量時(shí)刪除了 .value 的必要性。啟用后它在全球范圍內(nèi)可用。
5.Class API
Class API 已經(jīng)可用很長(zhǎng)時(shí)間了。通常與 Typescript 搭配使用是 Vue 2 的可靠選擇,并且被認(rèn)真考慮為默認(rèn)的 Vue 3 語(yǔ)法。
但經(jīng)過(guò)多次長(zhǎng)時(shí)間的討論后,它被放棄了,取而代之的是 Composition API。
它在 Vue 3 中可用,但工具嚴(yán)重缺乏,官方建議遠(yuǎn)離它。無(wú)論如何,如果您真的喜歡使用類(lèi),您的組件將看起來(lái)像這樣。
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
import AnotherComponent from './components/AnotherComponent.vue'
@Options({
components: {
AnotherComponent
}
})
export default class Counter extends Vue {
counter = 0;
get double(): number {
return this.counter * 2;
}
increase(): void {
this.quantity++;
}
}
</script>
<template>
<div class="wrapper">
<button @click="increase">Increase</button>
{{ counter }}
{{ double }}
</div>
</template>
結(jié)論
那哪個(gè)最好呢?這取決于典型的反應(yīng),盡管在這種情況下并非如此。從 Vue 2 遷移時(shí),選項(xiàng)和類(lèi) API 可以用作中間步驟,但它們不應(yīng)該是您的首選。
如果您沒(méi)有構(gòu)建階段,則組合 API 設(shè)置是唯一的選擇,但由于大多數(shù)項(xiàng)目都是使用 Webpack 或 Vite 生成的,因此使用腳本設(shè)置既是可能的,也是鼓勵(lì)的,因?yàn)榇蠖鄶?shù)可訪問(wèn)的文檔都使用這種方法。