vueドラッグ
14077 ワード
スムーズではなく、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>