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")