case
View 2
Advantages; It has been agreed on the location of learning and using, and writing code.
Disadvantages: Data and business logic are scattered in N places in the same file. With the increase of business complexity, the code organization on the left side of the animation may appear, which is not conducive to management and maintenance.
<template>
<div class="container">
<p>X 轴:{
{ x }} Y 轴:{
{ y }}</p>
<hr />
<div>
<p>{
{ count }}</p>
<button @click="add()">自增</button>
</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
// !#Fn1
x: 0,
y: 0,
// ?#Fn2
count: 0
}
},
mounted() {
// !#Fn1
document.addEventListener('mousemove', this.move)
},
methods: {
// !#Fn1
move(e) {
this.x = e.pageX
this.y = e.pageY
},
// ?#Fn2
add() {
this.count++
}
},
destroyed() {
// !#Fn1
document.removeEventListener('mousemove', this.move)
}
}
</script>
Advantages: *data* and *business logic* of the same function can be organized together for easy reuse and maintenance.
Disadvantages: It requires good code organization and splitting ability, relatively easy to use than Vue2.
Note: In order to allow everyone to better filter to the Vue3.0 version, the Vue2.x option API is currently supported.
链接: why-composition-api、composition-api-doc。
<template>
<div class="container">
<p>X 轴:{
{ x }} Y 轴:{
{ y }}</p>
<hr />
<div>
<p>{
{ count }}</p>
<button @click="add()">自增</button>
</div>
</div>
</template>
<script>
import { onMounted, onUnmounted, reactive, ref, toRefs } from 'vue'
export default {
name: 'App',
setup() {
// !#Fn1
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)
})
// ?Fn2
const count = ref(0)
const add = () => {
count.value++
}
// 统一返回数据供模板使用
return {
...toRefs(mouse),
count,
add
}
}
}
</script>