• 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")
    
  • 相关阅读:
    super与this的比较
    队列学习小结
    最左原则
    show processlist
    循环
    打印偶数
    发布模块
    eval函数
    文件
    模块
  • 原文地址:https://www.cnblogs.com/angfl/p/13865093.html
Copyright © 2020-2023  润新知