組合API Compositon API
vue3中使用組合api
- 寫法
- 代碼風(fēng)格:一個功能邏輯的代碼組織在一起(包含數(shù)據(jù)稚照,函數(shù)...)
- 優(yōu)點(diǎn):功能邏輯復(fù)雜繁多情況下弱恒,各個功能邏輯代碼組織再一起义起,便于閱讀和維護(hù)
- 缺點(diǎn):需要有良好的代碼組織能力和拆分邏輯能力,PS:大家沒問題昼汗。
- 補(bǔ)充:支持vue2.x選項(xiàng)API寫法
<template>
<div class="container">
<div>鼠標(biāo)位置:</div>
<div>X軸:{{x}}</div>
<div>Y軸:{{y}}</div>
<hr>
<div>{{count}} <button @click="add()">自增</button></div>
</div>
</template>
<script>
import { onMounted, onUnmounted, reactive, ref, toRefs } from 'vue'
export default {
name: 'App',
setup () {
// 鼠標(biāo)移動邏輯
const mouse = reactive({
x: 0,
y: 0
})
const move = e => {
mouse.x = e.pageX
mouse.y = e.pageY
}
onMounted(()=>{
document.addEventListener('mousemove',move)
})
onUnmounted(()=>{
document.removeEventListener('mousemove',move)
})
// 累加邏輯
const count = ref(0)
const add = () => {
count.value ++
}
// 返回數(shù)據(jù)
return {
...toRefs(mouse),
count,
add
}
}
}
</script>
選項(xiàng)API Options API
- 代碼風(fēng)格:data選項(xiàng)寫數(shù)據(jù)励烦,methods選項(xiàng)寫函數(shù)...屉栓,一個功能邏輯的代碼分散堤框。
- 優(yōu)點(diǎn):易于學(xué)習(xí)和使用蜈抓,寫代碼的位置已經(jīng)約定好
- 缺點(diǎn):代碼組織性差,相似的邏輯代碼不便于復(fù)用,邏輯復(fù)雜代碼多了不好閱讀棺亭。
- 補(bǔ)充:雖然提供mixins用來封裝邏輯凄敢,但是出現(xiàn)數(shù)據(jù)函數(shù)覆蓋的概率很大涝缝,不好維護(hù)。
<template>
<div class="container">
<div>鼠標(biāo)位置:</div>
<div>X軸:{{x}}</div>
<div>Y軸:{{y}}</div>
<hr>
<div>{{count}} <button @click="add()">自增</button></div>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
x: 0,
y: 0,
count: 0
}
},
mounted() {
document.addEventListener('mousemove', this.move)
},
methods: {
move(e) {
this.x = e.pageX
this.y = e.pageY
},
add () {
this.count++
}
},
destroyed() {
document.removeEventListener('mousemove', this.move)
}
}
</script>