vue3笔记3 组合式API复用
可以把组件中使用组合式API创建的逻辑抽取出来封装成可复用的模块
类似vue2中的mixin
定义模块
GetMousePoint.js
import {onBeforeUnmount, onMounted, reactive} from "vue";
export default function () {
let point = reactive({
x: 0,
y: 0
})
function savePoint(event) {
point.x = event.pageX
point.y = event.pageY
}
onMounted(() => {
window.addEventListener('click', savePoint)
})
onBeforeUnmount(() => {
window.removeEventListener('click', savePoint)
})
return point;
}
使用模块
HelloWorld.vue
import GetMousePoint from "./GetMousePoint"
...
setup() {
let point = GetMousePoint()
return {
point
}
}