slider-comp.js 3.09 KB
export default {
	props: ["min", "max", "value"],
	data() {
		return {
			slider: null, //滚动条DOM元素
			thunk: null, //拖拽DOM元素
			per: this.value || 0, //当前值

			flags: false,
			curWidth: 0,
			disX: 0
		};
	},
	methods: {
		end(e) {
			this.flags = false;
		},
		down(event) {
			let _this = this;
			var touch;
			if (event.touches) {
				touch = event.touches[0];
			} else {
				touch = event;
			}
			let e = touch;

			_this.curWidth = parseInt(_this.width);
			_this.disX = e.clientX;
			_this.flags = true;
		},
		move(event) {
			let _this = this;
			if (_this.flags) {
				var touch;
				if (event.touches) {
					touch = event.touches[0];
				} else {
					touch = event;
				}
				let e = touch;

				let disX = _this.disX;
				let width = _this.curWidth;

				// 拖拽的时候获取的新width
				var newWidth = e.clientX - disX + width;
				// console.log("this.slider.offsetWidth:", this.slider.offsetWidth);
				// console.log("this.thunk.offsetWidth:", this.thunk.offsetWidth);

				// 拖拽的时候得到新的百分比
				var scale = newWidth / _this.slider.offsetWidth;
				_this.per = Math.ceil((_this.max - _this.min) * scale + _this.min);
				_this.per = Math.max(_this.per, _this.min);
				_this.per = Math.min(_this.per, _this.max);
				_this.$emit("input", _this.per);
			}

		},
		initData() {
			var _this = this;
			this.$nextTick(() => {

				// 监听PC和移动端事件				
				this.thunk.addEventListener("mousedown", (e) => {
					event.preventDefault();
					_this.down(e);
				}, false);
				this.thunk.addEventListener("touchstart", (e) => {
					event.preventDefault();
					_this.down(e);
				}, false);

				document.addEventListener("mousemove", (e) => {
					event.preventDefault();
					_this.move(e);
				}, false);

				document.addEventListener("touchmove", (e) => {
					event.preventDefault();
					_this.move(e);
				}, false);

				document.addEventListener("mouseup", (e) => {
					event.preventDefault();
					_this.end(e);
				}, false);

				document.addEventListener("touchend", (e) => {
					event.preventDefault();
					_this.end(e);
				}, false);
			});
		}
	},
	//渲染到页面的时候
	mounted() {
		this.slider = this.$refs.slider;
		this.thunk = this.$refs.trunk;
		this.initData();
		window.addEventListener('resize', () => {
			this.initData();
			// console.log("scale:", this.scale);

			// 改per的值,强制刷新计算属性computed
			let tempPer = this.per;
			this.per = 0;
			this.per = tempPer;
		}, false);
	},

	computed: {
		// 设置一个百分比,提供计算slider进度宽度和trunk的left值
		// 对应公式为  当前值-最小值/最大值-最小值 = slider进度width / slider总width
		// trunk left =  slider进度width + trunk宽度/2
		scale() {
			return (this.per - this.min) / (this.max - this.min);
		},
		width() {
			if (this.slider) {
				return this.slider.offsetWidth * this.scale + "px";
			} else {
				return 0 + "px";
			}
		},
		left() {
			if (this.slider) {
				return (
					this.slider.offsetWidth * this.scale -
					this.thunk.offsetWidth / 2 +
					"px"
				);
			} else {
				return 0 + "px";
			}
		}
	}
};