什么,你还不会 vue 拉伸指令?
前言
在我们项目开发中,经常会有布局拉伸的需求,接下来 让我们一步步用 vue指令
实现这个需求
先上 Demo 地址
常规使用
解决拉伸触发时机
既然我们使用了指令的方式,也就是牺牲了组件方式的绑定事件的便捷性.
那么我们如何来解决这个触发时机的问题呢?
在参考了 Element UI
的表格拉伸功能后,笔者受到了启发
有点抽象,这个红色区域可不是真实节点,只是笔者模拟的一个 boder-right
多说无益 直接上代码吧
const pointermove = e => {
const { right } = el.getBoundingClientRect() // 获取到节点的右边界
const { clientX } = e // 此时鼠标位置
if (right - clientX < 8) // 表明在右边界的 8px 的过渡区 可以拉伸
}
实现一个简单的右拉伸
下面让我们来实现一个简单的右拉伸功能, 既然用指令 肯定是越简单越好
笔者决定用 vue提供的 修饰符, v-resize.right
实现 v-resize.right
1.首先我们创建两个相邻 div
<template>
<div class="container">
<div
v-resize.right
class="left"
/>
<div class="right" />
</div>
</template>
<style lang="scss" scoped>
.container {
width: 400px;
height: 100px;
> div {
float: left;
height: 100%;
width: 50%;
}
.left {
background-color: lightcoral;
}
.right {
background-color: lightblue;
}
}
</style>
2.实现 resize 触发时机
export const resize = {
inserted: function(el, binding) {
el.addEventListener('pointermove', (e) => {
const { right } = el.getBoundingClientRect()
if (right - e.clientX < 8) {
// 此时表明可以拉伸,时机成熟
el.style.cursor = 'col-resize'
} else {
el.style.cursor = ''
}
})
}
}
3.实现右拉伸功能
el.addEventListener('pointerdown', (e) => {
const rightDom = el.nextElementSibling // 获取右节点
const startX = e.clientX // 获取当前点击坐标
const { width } = el.getBoundingClientRect() // 获取当前节点宽度
const { width: nextWidth } = rightDom.getBoundingClientRect() // 获取右节点宽度
el.setPointerCapture(e.pointerId) // HTML5 的 API 自行百度~
const onDocumentMouseMove = (e) => {
const offsetX = e.clientX - startX // 此时的 x 坐标偏差
// 更新左右节点宽度
el.style.width = width + offsetX + 'px'
rightDom.style.width = nextWidth - offsetX + 'px'
}
// 因为此时我们要在整个屏幕移动 所以我们要在 document 挂上 mousemove
document.addEventListener('mousemove',onDocumentMouseMove)
让我们看看此时的效果
会发现有两个问题
- 左边宽度会>左右之和,右边宽度会 < 0
- 当我们鼠标弹起的时候 还能继续拉伸
让我们首先解决第一个问题
方案一:限制最小宽度
const MIN_WIDTH = 10
document.addEventListener('mousemove', (e) => {
const offsetX = e.clientX - startX // 此时的 x 坐标偏差
+if (width + offsetX < MIN_WIDTH || nextWidth - offsetX < MIN_WIDTH) return
// 更新左右节点宽度
el.style.width = width + offsetX + 'px'
rightDom.style.width = nextWidth - offsetX + 'px'
})
第二个问题,其实非常简单
方案二:鼠标弹起后释放对应拉伸事件
el.addEventListener('pointerup', (e) => {
el.releasePointerCapture(e.pointerId)
document.removeEventListener('mousemove', onDocumentMouseMove)
})
此时最最最基础的 v-resize
左右拉伸版本 我们已经实现了,来看下效果吧
看下此时的完整代码
export const resize = {
inserted: function (el, binding) {
el.addEventListener('pointermove', (e) => {
const { right } = el.getBoundingClientRect()
if (right - e.clientX < 8) {
// 此时表明可以拉伸
el.style.cursor = 'col-resize'
} else {
el.style.cursor = ''
}
})
const MIN_WIDTH = 10
el.addEventListener('pointerdown', (e) => {
const rightDom = el.nextElementSibling // 获取右节点
const startX = e.clientX // 获取当前点击坐标
const { width } = el.getBoundingClientRect() // 获取当前节点宽度
const { width: nextWidth } = rightDom.getBoundingClientRect() // 获取右节点宽度
el.setPointerCapture(e.pointerId) // HTML5 的 API 自行百度~
const onDocumentMouseMove = (e) => {
const offsetX = e.clientX - startX // 此时的 x 坐标偏差
if (width + offsetX < MIN_WIDTH || nextWidth - offsetX < MIN_WIDTH) {
return
}
// 更新左右节点宽度
el.style.width = width + offsetX + 'px'
rightDom.style.width = nextWidth - offsetX + 'px'
}
// 因为此时我们要在整个屏幕移动 所以我们要在 document 挂上 mousemove
document.addEventListener('mousemove', onDocumentMouseMove)
el.addEventListener('pointerup', (e) => {
el.releasePointerCapture(e.pointerId)
document.removeEventListener('mousemove', onDocumentMouseMove)
})
})
},
}
作为 一名 优秀的前端性能优化专家
, 我想你此刻已经要吐槽了,这么多 EventListener
都不移除吗? 是的,后续代码我们将会移除这些被绑定的事件(此处非重点 不做赘叙)
实现完 右拉伸
想必你对 左,上,下拉伸 也已经有了自己的思路
开始进阶
接下来让我们看下这种场景
我们 想实现一个 两边能同时拉伸的功能, 也就是
v-resize.left.right
实现左右拉伸功能
这种场景比较复杂,就需要我们维护一个拉伸方向上的变量 position
实现 v-resize.left.right
export const resize = {
inserted: function (el, binding) {
let position = '',
resizing = false
el.addEventListener('pointermove', (e) => {
if (resizing) return
const { left, right } = el.getBoundingClientRect()
const { clientX } = e
if (right - clientX < 8) {
position = 'right' // 此时表明右拉伸
el.style.cursor = 'col-resize'
} else if (clientX - left < 8) {
position = 'left' // 此时表明左拉伸
el.style.cursor = 'col-resize'
} else {
position = ''
el.style.cursor = ''
}
})
const MIN_WIDTH = 10
el.addEventListener('pointerdown', (e) => {
if (position === '') return
const sibling = position === 'right' ? el.nextElementSibling : el.previousElementSibling // 获取相邻节点
const startX = e.clientX // 获取当前点击坐标
const { width } = el.getBoundingClientRect() // 获取当前节点宽度
const { width: siblingWidth } = sibling.getBoundingClientRect() // 获取右节点宽度
el.setPointerCapture(e.pointerId) // HTML5 的 API 自行百度~
const onDocumentMouseMove = (e) => {
resizing = true
if (position === '') return
const offsetX = e.clientX - startX
const _elWidth = position === 'right' ? width + offsetX : width - offsetX //判断左右拉伸 所影响的当前节点宽度
const _siblingWidth = position === 'right' ? siblingWidth - offsetX : siblingWidth + offsetX //判断左右拉伸 所影响的相邻节点宽度
if (_elWidth <= MIN_WIDTH || _siblingWidth <= MIN_WIDTH) return
// 更新左右节点宽度
el.style.width = _elWidth + 'px'
sibling.style.width = _siblingWidth + 'px'
}
document.addEventListener('mousemove', onDocumentMouseMove)
el.addEventListener('pointerup', (e) => {
position = ''
resizing = false
el.releasePointerCapture(e.pointerId)
document.removeEventListener('mousemove', onDocumentMouseMove)
})
})
},
}
看下此时的效果
非常丝滑, 当然 我们还需要考虑 传递 最小宽度
最大宽度
过渡区
等多种业务属性,但是这对于各位看官来说都是鸡毛蒜皮的小事. 自行改造就行了
完整代码
const MIN_WIDTH = 50
const MIN_HEIGHT = 50
const elEventsWeakMap = new WeakMap()
function getElStyleAttr(element, attr) {
const styles = window.getComputedStyle(element)
return styles[attr]
}
function getSiblingByPosition(el, position) {
const siblingMap = {
left: el.previousElementSibling,
right: el.nextElementSibling,
bottom: el.nextElementSibling,
top: el.previousElementSibling
}
return siblingMap[position]
}
const initResize = ({
el,
positions,
minWidth = MIN_WIDTH,
minHeight = MIN_HEIGHT
}) => {
if (!el) return
const resizeState = {}
const defaultCursor = getElStyleAttr(el, 'cursor')
const elStyle = el.style
const canLeftResize = positions.includes('left')
const canRightResize = positions.includes('right')
const canTopResize = positions.includes('top')
const canBottomResize = positions.includes('bottom')
if (!canLeftResize && !canRightResize && !canTopResize && !canBottomResize) {
return
} // 未指定方向
const pointermove = (e) => {
if (resizeState.resizing) return
const { left, right, top, bottom } = el.getBoundingClientRect()
const { clientX, clientY } = e
// 左右拉伸
if (canLeftResize || canRightResize) {
if (clientX - left < 8) resizeState.position = 'left'
else if (right - clientX < 8) resizeState.position = 'right'
else resizeState.position = ''
if (resizeState.position === '') {
elStyle.cursor = defaultCursor
} else {
elStyle.cursor = 'col-resize'
e.stopPropagation()
}
} else if (canTopResize || canBottomResize) {
// 上下拉伸
if (clientY - top < 8) resizeState.position = 'top'
else if (bottom - clientY < 8) resizeState.position = 'bottom'
else resizeState.position = ''
if (resizeState.position === '') {
elStyle.cursor = defaultCursor
} else {
elStyle.cursor = 'row-resize'
e.stopPropagation()
}
}
}
const resizeEnd = (e) => {
e.stopPropagation()
resizeState.position = ''
resizeState.resizing = false
elStyle.cursor = defaultCursor
el.releasePointerCapture(e.pointerId)
document.removeEventListener('mousemove', resizeState.onDocumentMouseMove)
resizeState.onDocumentMouseMove = null
}
// todo 只有在命中mousemove可拖拽的情况下 添加事件
const pointerdown = (e) => {
const { resizing, position } = resizeState
if (resizing || !position) return
if (position) e.stopPropagation() // 如果当前节点存在拉伸方向 需要组织冒泡
el.setPointerCapture(e.pointerId)
const isFlex = getElStyleAttr(el.parentNode, 'display') === 'flex'
resizeState.resizing = true
resizeState.startMouseX = e.clientX
resizeState.startMouseY = e.clientY
const { width, height } = el.getBoundingClientRect()
const containerSibling = getSiblingByPosition(el, position)
if (!containerSibling) {
console.error('未找到兄弟节点', position)
return
}
const rectSibling = containerSibling.getBoundingClientRect()
const { startMouseX, startMouseY } = resizeState
const onDocumentMouseMove = (e) => {
if (!resizeState.resizing) return
elStyle.cursor =
canLeftResize || canRightResize ? 'col-resize' : 'col-row'
const { clientX, clientY } = e
if (position === 'left' || position === 'right') {
const offsetX = clientX - startMouseX
const elWidth = position === 'right' ? width + offsetX : width - offsetX
const containerSiblingWidth =
position === 'right'
? rectSibling.width - offsetX
: rectSibling.width + offsetX
if (elWidth <= minWidth || containerSiblingWidth <= minWidth) return
el.style.width = elWidth + 'px'
containerSibling.style.width = containerSiblingWidth + 'px'
if (isFlex) {
el.style['min-width'] = elWidth + 'px'
containerSibling.style['min-width'] = containerSiblingWidth + 'px'
}
} else if (position === 'top' || position === 'bottom') {
const offsetY = clientY - startMouseY
const elHeight =
position === 'bottom' ? height + offsetY : height - offsetY
const containerSiblingHeight =
position === 'bottom'
? rectSibling.height - offsetY
: rectSibling.height + offsetY
if (elHeight <= minHeight || containerSiblingHeight <= minHeight) return
el.style.height = elHeight + 'px'
containerSibling.style.height = containerSiblingHeight + 'px'
if (isFlex) {
el.style['min-height'] = elHeight + 'px'
containerSibling.style['min-height'] = containerSiblingHeight + 'px'
}
}
}
resizeState.onDocumentMouseMove = onDocumentMouseMove
document.addEventListener('mousemove', onDocumentMouseMove)
}
const bindElEvents = () => {
el.addEventListener('pointermove', pointermove)
el.addEventListener('pointerleave', resizeEnd)
el.addEventListener('pointerup', resizeEnd)
el.addEventListener('pointerdown', pointerdown)
}
const unBindElEvents = () => {
el.removeEventListener('pointermove', pointermove)
el.removeEventListener('pointerleave', resizeEnd)
el.removeEventListener('pointerup', resizeEnd)
el.removeEventListener('pointerdown', pointerdown)
}
bindElEvents()
// 设置解绑事件
elEventsWeakMap.set(el, unBindElEvents)
}
export const resize = {
inserted: function(el, binding) {
const { modifiers, value: { minWidth, minHeight } = {}} = binding
const positions = Object.keys(modifiers)
initResize({ el, positions, minWidth, minHeight })
},
unbind: function(el) {
const unBindElEvents = elEventsWeakMap.get(el)
unBindElEvents()
}
}
参考文章
写在最后
未来想做的还有很多
- 支持 % 比的配置
- 支持 嵌套类型的 父子孙节点的更新
- ...
个人能力有限 如有不对,欢迎指正🌟 如有帮助,建议小心心大拇指三连🌟
转载自:https://juejin.cn/post/7250402828378914876