Vue3.0组合式API案例
<template>
<div>
<div>
坐标x:{{x}}
</div>
<div>
坐标y:{{y}}
</div>
<div>{{count}}</div>
<button @click="add">累加</button>
</div>
</template>
<script>
import { reactive,onMounted,toRefs, onUnmounted,ref} from 'vue'
const usemouse=()=>{
//1.记录鼠标坐标位置
//2.声明一个响应式数据它是一个对象包含下x,y
const mouse = reactive({
x:0,
y:0
})
//等dom渲染完毕去监听事件的变化
//在move函数中修改响应的数据
const move =(e)=>{
mouse.x = e.pageX;
mouse.y = e.pageY;
}
onMounted(()=>{
document.addEventListener('mousemove',move);
})
//组件消耗删除事件
onUnmounted(()=>{
//当组件销毁将绑定的事件销毁
document.removeEventListener('mousemove',move);
})
return mouse
}
export default {
name:'App',
setup(){
const mouse = usemouse;//将usemouse与之前的代码剥离
//数字累加
const count = ref(0)
const add=()=>{
count.value ++
}
return {...toRefs(mouse),count,add}
}
}
</script>
<style lang="scss" scoped>
</style>