首页 > IT职业 > IT图书 > Vue3 简单使用,调用实时监控鼠标指针x,y坐标
Vue3 简单使用,调用实时监控鼠标指针x,y坐标
const {createApp,reactive,toRefs,onMounted,onUnmounted,computed}= Vue
鼠标位置实时监听
注意点:
beforeCreate -> 使用 setup()
created -> 使用 setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
errorCaptured -> onErrorCaptured
ref 用于声明基础数据类型,该属性值发生更改,都会发生响应式变化
<div id = 'app'>
<p @click='add'>{{counter}}</p>
</div>
setup(){
const counter = ref(0);
function add(){
counter.value++ ;// 用ref 定义的响应式数据,修改的时候必须是 xxx.value形式去更改不然会报错,但是模板里用的时候可以直接用{{xxx}}
}
return {
counter
}
}
reactive
setup(){
const state = reactive({name:'zzz',age:18});
return {state}
}
function useMouse(){
const state = reactive({x:0,y:0});
const update = e=>{
state.x = e.pageX;
state.y = e.pageY;
}
onMounted(()=>{
window.addEventListener('mousemove',update);
})
onUnmounted(()=>{
window.removeEventListener('mousemove',update);
})
return toRefs(state);
}
const myComp = {
template:`<div>x : {{x}} y :{{y}}</div>`,
setup(){
const {x,y} = useMouse();
//这里的 x 和 y 都是ref 的 属性值,响应式没有丢失
return {x,y}
}
}
createApp(myComp).mount("#app")
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/930/viewspace-2826452/ ,如需转载,请注明出处,否则将追究法律责任。