实现vue图片缩放方式-拖拽组件

目录

  • 实现效果如下
  • 父组件如下
  • 子组件imgbox.vue如下

实现效果如下
这几天做了个没做过的组件,以此记录下,需要的效果是在一个dom内,缩放拖拽图片。
封装的子组件imgbox.Vue。父组件中使用,需要在父组件中准备一个盒子用来装图片,在这个盒子中可以缩放拽拽图片。

父组件如下 父组件html部分
实现vue图片缩放方式-拖拽组件
文章图片
实现vue图片缩放方式-拖拽组件
文章图片
实现vue图片缩放方式-拖拽组件
文章图片

子组件接受父组件传递参数,自定义指令
export default {components:{},props:['config'],data(){return {imgsrc:"",//图片的路径}},directives:{//注册指令drag:function(el){let dragBox = el; //获取当前元素dragBox.onmousedown = e => {e.preventDefault(); //算出鼠标相对元素的位置let disX = e.clientX - dragBox.offsetLeft; let disY = e.clientY - dragBox.offsetTop; document.onmousemove = e => {//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置e.preventDefault(); let left = e.clientX - disX; let top = e.clientY - disY; //移动当前元素dragBox.style.left = left + "px"; dragBox.style.top = top + "px"; }; document.onmouseup = e => {e.preventDefault(); //鼠标弹起来的时候不再移动document.onmousemove = null; //预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)document.onmouseup = null; }; }}},watch:{config:function(val){this.imgsrc = https://www.it610.com/article/val.imgsrc}},computed:{scaleFun:function(){return `transform:scale(${this.config.scale})`}},created(){},methods:{clickEnlarge(){//点击放大let data = https://www.it610.com/article/this.configthis.$emit('enlarge',data)},clickNarrow(){//点击缩小let data = https://www.it610.com/article/this.configthis.$emit('narrow',data)}},}

子组件css
.myDiv{width: 100%; height: 100%; position: relative; overflow: hidden; img{width: 100%; height: 100%; position: relative; }.btnbox{display: flex; position: absolute; top: 20px; left: 20px; width: 70px; height: 20px; justify-content: space-around; z-index: 99; img{width: 20px; height: 20px; opacity: 0.7; cursor: pointer; display: inline-block; }}}

【实现vue图片缩放方式-拖拽组件】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读