效果如下
GIF 2023-11-8 14-49-43.gif
:
原理:
收縮按鈕是相對父節點定位的。點擊后通過更改父組件的left 值進行展開收縮,收縮時left為-1 * 父節點寬度, 展開時還原為初始狀態。
源碼:
<!--
author:yangfeng
date:20231107
在此組件父節點添加一個展開收縮的按鈕,點擊時收縮父組件,再次點擊展開父組件
【原理: 通過更改父組件的left 值進行展開收縮,收縮時left為-1 * 父節點寬度, 展開時還原為初始狀態】
【注意:組件是相對于父組件定位的!】
-->
<template>
<div :class="{ 'ec-arrow': true }" @click="trigger" ref="arrowRefDom">
<img v-show="open" src="@/assets/ss-left.png" />
<img v-show="!open" src="@/assets/ss-right.png" />
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
const props = defineProps({
// 是開啟還是關閉狀態
open: {
type: Boolean,
default: true
}
})
const emit = defineEmits([
'update:open', // v-model
'click'
])
const arrowRefDom = ref()
let parentNodeCssInfo = {} // 父節點初始樣式
const trigger = () => {
let bool = !props.open
emit('update:open', bool)
emit('click', bool)
}
/**
* 顯示隱藏父節點panel
* @param {*} bool true:展開父節點 false:收縮父節點
*/
const hideOrShowParentNode = (bool = false) => {
let parentNode = arrowRefDom.value.parentNode
if (!parentNode) return
if (bool) { // 展開父節點
parentNode.style.left = parentNodeCssInfo.left || 0
} else { // 折疊父節點
parentNode.style.left = -1 * parentNode.offsetWidth + 'px'
}
}
// 獲取樣式
const getStyle = (htmlNode, str) => {
if(!htmlNode || !str) return ''
if (htmlNode.currentStyle) { // ie
return htmlNode.currentStyle[str]
} else {
return window.getComputedStyle(htmlNode, null)[str]
}
}
// 初始化
const init = () => {
// 存儲父節點信息
let parentNode = arrowRefDom.value.parentNode
if (!parentNode) return
parentNode.style.transition = 'left ease 0.5s'
parentNodeCssInfo = {
left: getStyle(parentNode, 'left')
}
// 初始狀態
hideOrShowParentNode(props.open)
}
watch(()=>props.open,(newVal)=>{
hideOrShowParentNode(newVal)
})
onMounted(() => {
init()
})
</script>
<style lang="scss" scoped>
$width: 26px;
$height: 77px;
.ec-arrow {
width: $width;
height: $height;
top: 50%;
right: -1 * $width;
margin-top: -0.5 * $height;
position: absolute;
cursor: pointer;
z-index: 99;
img {
width: 100%;
height: 100%;
}
}
</style>
圖標:
image.png
調用方式:
image.png
總結
代碼很簡單,考慮到比較常用就分享給大家,遇到panel展開方向不一樣的自行擴展!
若對你有幫助,請點個贊吧,若能打賞不勝感激,謝謝支持!
本文地址:http://www.lxweimin.com/p/d4f9f5107aab?v=1699426268971,轉載請注明出處,謝謝。