提问人:MAHA OUEGHLANI 提问时间:2/9/2023 更新时间:2/9/2023 访问量:387
Vue.js : 带有两个手柄的范围滑块
Vue.js : Range slider with two handles
问:
我想创建一个vue js组件,其中包含一个带有两个句柄的小时范围滑块。
我使用 vue3 + vite.js
我尝试了此代码来实现组件,但是当我拖动其中一个句柄时,出现错误
代码:这是模板:
<template>
<div>
<input type="range" ref="rangeInput" v-model="rangeValue" @input="updateRange"/>
<div class="range-slider">
<div class="handle" :style="{left: leftHandle + '%'}" @mousedown="startHandleDrag(1)">
{{ formatHour(rangeValue[0]) }}
</div>
<div class="handle" :style="{left: rightHandle + '%'}" @mousedown="startHandleDrag(2)">
{{ formatHour(rangeValue[1]) }}
</div>
</div>
</div>
</template>
这是脚本:
<script>
export default {
data() {
return {
rangeValue: [8, 18],
handleDragging: 0
};
},
computed: {
leftHandle() {
return this.rangeValue[0];
},
rightHandle() {
return this.rangeValue[1];
}
},
methods: {
updateRange(event) {
const value = event.target.value;
const range = this.rangeValue;
if (this.handleDragging === 1) {
range[0] = value[0];
} else if (this.handleDragging === 2) {
range[1] = value[1];
} else {
range[0] = value[0];
range[1] = value[1];
}
this.rangeValue = range;
},
startHandleDrag(handle) {
this.handleDragging = handle;
document.addEventListener("mouseup", this.stopHandleDrag);
document.addEventListener("mousemove", this.updateRange);
},
stopHandleDrag() {
this.handleDragging = 0;
document.removeEventListener("mouseup", this.stopHandleDrag);
document.removeEventListener("mousemove", this.updateRange);
},
formatHour(value) {
return value + ":00";
}
}
};
</script>
任何解决它的想法!!
答:
0赞
Moritz Ringler
2/9/2023
#1
在 和 中,绑定到 mousemove 事件:startHandleDrag()
stopHandleDrag()
updateRange()
document.addEventListener("mousemove", this.updateRange);
这有两个问题:
- 事件的目标是光标下的元素。这可以是任何元素,除非它恰好是输入,否则它不会有属性(如果有,它不会包含数组)。如果确实要使用“mousemove”事件,请使用光标坐标,如 或 。
mousemove
value
pageX
pageX
- 将其绑定为函数指针 (),当从侦听器调用时,将引用 。为避免这种情况,请使用箭头函数 () 或绑定 ()。
addEventListener("mousemove", this.updateRange)
this
element.target
addEventListener("mousemove", (e) => this.updateRange(e))
this
addEventListener("mousemove", this.updateRange.bind(this))
我不完全明白你想用句柄做什么,但我的猜测是添加和删除听众是一种解决方法,你真的想让它们可拖动吗?如果是这样,请查看拖动事件。希望对您有所帮助!
评论