vue中实现组件跟随鼠标位置弹出效果

在这里插入图片描述
实现鼠标放置在“我的”上时出现卡片,卡片位置跟随鼠标。当鼠标移除卡片时卡片隐藏。
当鼠标移入时获取鼠标坐标,并把父组件的鼠标位置通过prop传给子组件。
在这里插入图片描述

toCenter(event){
  const{x,y}=event
  this.mouse_x=x;
  this.mouse_y=y;
  this.showCenter=true;
},

在这里插入图片描述
子组件通过动态绑定style改变div坐标。
在这里插入图片描述
注意!!!
在这里插入图片描述
一开始没用watch,而是在data里直接修改,如上所示。
这样会出现刷新以后data获取不到prop中的属性值。如下图
在这里插入图片描述
加上watch监听prop中x,y变化,这样可以解决。最终版本如下:

  data(){
   return {
     content:['上传头像','修改资料','退出账号','在线反馈'],
     sty:{
       top:'',
       left:''
     }
   }
  },
 watch:{
   x:function(val){
     this.sty.left=(val+10)+'px'
   },
   y:function(val){
     this.sty.top=(val+30)+'px'
   }
 }
}

对了,在组件上添加鼠标移出事件就可以实现鼠标移出卡片关闭。
在这里插入图片描述

leaveCenter(){
  this.showCenter=false;
}

猜你喜欢

转载自blog.csdn.net/m0_60721514/article/details/123371832#comments_21977126
今日推荐