常规
不是很顺畅,而且也是DOM操作,不是符合vue的意义,尽量不要改DOM元素,要用数据驱动,少用 this.$refs
<style>
#box {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: red;
}
</style>
<div id="app">
<div id="box" ref="box" @mousedown="down" @mousemove="move" @mouseup="up" :style="{left, top}"></div>
</div>
<script src="vue.js"></script>
<script>
let app = new Vue({
el:'#app',
data:function(){
return{
isDown: false,
x:0,
y:0,
left:'',
top:''
}
},
methods:{
down(e){
this.isDown=true;
this.x=e.clientX-this.$refs.box.offsetLeft;
this.y=e.clientY-this.$refs.box.offsetTop;
},
move(e){
if(this.isDown){
// this.$refs.box.style.left=e.clientX-this.x+'px';
// this.$refs.box.style.top=e.clientY-this.y+'px';
//尽量少用Dom操作,可改为
this.left=e.clientX-this.x+'px';
this.top=e.clientY-this.y+'px';
}
},
up(){
this.isDown=false;
}
}
})
</script>
自定义指令
推荐使用: 指令作用到元素身上的时候被执行 测试地址:http://jsrun.net/HTgKp
<div id="app">
<div id="box1" v-drag.limit></div>
<div id="box2" v-drag></div>
</div>
<script src="js/vue.js"></script>
<script>
/*
* 创建自定义的指令
* */
Vue.directive('drag', {
// 当指令绑定到元素上的时候执行
bind(el, binding) {
// console.log('bind');
// 当前指令绑定的dom元素
//console.log(el);
// 指令传入的参数、修饰符、值 v-指令名称:参数.修饰符=值
// console.log(binding)
el.onmousedown = function(e) {
let disX = e.clientX - el.offsetLeft;
let disY = e.clientY - el.offsetTop;
document.onmousemove = function(e) {
let L = e.clientX - disX;
let T = e.clientY - disY;
if (binding.modifiers.limit) {
if (L < 0) {
L = 0;
}
}
el.style.left = L + 'px';
el.style.top = T + 'px';
};
document.onmouseup = function() {
document.onmousemove = null;
};
return false;
}
}
});
new Vue({
el: '#app'
});
</script>
移动端
<style>
.box {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: red;
}
</style>
<div id="app">
<div class="box" ref="box"
@mousedown="down" @touchstart="down"
@mousemove="move" @touchmove="move"
@mouseup="end" @touchend="end"
>
</div>
</div>
<script src="vue.js"></script>
<script>
let app = new Vue({
el:'#app',
data() {
return {
flags: false,
position: {
x: 0,
y: 0
},
nx: '', ny: '', dx: '', dy: '', xPum: '', yPum: '',
}
},
methods: {
down(){
this.flags = true;
var touch ;
if(event.touches){
touch = event.touches[0];
}else {
touch = event;
}
this.position.x = touch.clientX;
this.position.y = touch.clientY;
this.dx = this.$refs.box.offsetLeft;
this.dy = this.$refs.box.offsetTop;
},
move(){
if(this.flags){
var touch ;
if(event.touches){
touch = event.touches[0];
}else {
touch = event;
}
this.nx = touch.clientX - this.position.x;
this.ny = touch.clientY - this.position.y;
this.xPum = this.dx+this.nx;
this.yPum = this.dy+this.ny;
this.$refs.box.style.left = this.xPum+"px";
this.$refs.box.style.top = this.yPum +"px";
//阻止页面的滑动默认事件
document.addEventListener("touchmove",function(){
event.preventDefault();
},false);
}
},
//鼠标释放时候的函数
end(){
this.flags = false;
},
}
})
</script>