在Vue 2中,主要使用mixin来实现代码的重用。但到了Vue 3中,推荐使用Composition API + 自定义hooks来实现代码的重用。
自定义Hooks
首先定义一个hook,比如:src/hooks/usePos.js,将鼠标位置逻辑进行封装:
import { reactive, onMounted, onBeforeUnmount } from 'vue'
export default function() {
let pos = reactive({
x: 0,
y: 0
})
const savePos = event => {
pos.x = event.pageX
pos.y = event.pageY
}
onMounted(() => {
window.addEventListener('click', savePos)
})
onBeforeUnmount(() => {
window.removeEventListener('click', savePos)
})
return pos
}
调用该hook
在其他组件中调用这个hook时旧非常简洁了:
import usePos from '@src/hooks/usePos'
export default {
name: 'Hooktest',
setup() {
const pos = usePos()
// ...
return { pos }
}
}
这样就可以在UI部分使用返回的pos了。
通过这种方式,就可以把不同的API有机的组合在一起,实现组合功能:
setup() {
const xxx = useXXX();
const yyy = useYYY();
const zzz = useZZZ();
// ...
return { xxx, yyy, zzz }
}