Vue3 簡單使用,調用實時監控鼠標指針x,y坐標
Vue3 简单使用,调用实时监控鼠标指针x,y坐标
- 解构出我们要用的钩子函数
const {createApp,reactive,toRefs,onMounted,onUnmounted,computed}= Vue
-
鼠标位置实时监听
注意点:- v3里面数据响应式要通过reactive实现 => reactive({})
- 声明周期变化 v2 <----> v3
beforeCreate -> 使用 setup() created -> 使用 setup() beforeMount -> onBeforeMount mounted -> onMounted beforeUpdate -> onBeforeUpdate updated -> onUpdated beforeDestroy -> onBeforeUnmount destroyed -> onUnmounted errorCaptured -> onErrorCaptured
- ref 、 reactive 、 isRef
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")
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦