概念
mixin可以用来扩展组件,将公共逻辑进行抽离,在需要该逻辑的组件进行混入,采用策略模式****针对不同的属性进行合并,如果混入的数据和本身组件的数据冲突,采用“就近原则”,以组件的数据为准
混入方式
全局混入:用于编写插件
局部混入:复用逻辑
合并策略
核心:对象的合并处理
props、methods、inject、computed同名时会被替换
data会被合并
生命周期和watch会被合并成队列
components、directives、filters会在原型链上叠加
缺点
mixin中命名冲突、数据来源问题,vue3采用compositionAPI提取公共逻辑非常方便
vue3的mixin也被称为hooks
//实现监控鼠标移动坐标的功能
import {reactive,onMounted,onBeforeUnmount} from 'vue'
export default function(){
let point = reactive({
x:0,
y:0
})
function savePoint(event:any){
point.x = event.pageX
point.y = event.pageY
console.log(event.pageX,event.pageY)
}
onMounted(()=>{
window.addEventListener('click',savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
return point
}
使用
<script lang='ts' setup>
import { ref, reactive, toRefs, computed } from "vue";
import usepoint from '../src/hooks/usePoint'
const point = usepoint()
console.log('point', point)
</script>