ct/app/composables/useImageStyles.ts

83 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-10-13 13:51:40 +08:00
import {nextTick, watch, onMounted, type Ref} from 'vue'
/**
* Composable
* v-html
*/
export const useImageStyles = (
contentRef: Ref<string> | (() => string),
containerSelector: string = '.article-content',
options: {
maxWidth?: string
margin?: string
display?: string
boxSizing?: string
} = {}
) => {
// 默认配置
const defaultOptions = {
2025-10-13 14:50:45 +08:00
maxWidth: 'calc(100% - 0px)',
2025-10-13 13:51:40 +08:00
margin: '15px 0',
display: 'block',
boxSizing: 'border-box',
...options
}
/**
*
*/
const forceImageStyles = () => {
if (typeof document === 'undefined') return
const images = document.querySelectorAll(`${containerSelector} img`)
images.forEach((img: any) => {
// 强制设置样式
img.style.maxWidth = defaultOptions.maxWidth
img.style.height = 'auto'
img.style.width = 'auto'
img.style.display = defaultOptions.display
img.style.margin = defaultOptions.margin
img.style.boxSizing = defaultOptions.boxSizing
})
}
/**
*
*/
const processImageStyles = () => {
nextTick(() => {
forceImageStyles()
})
}
/**
*
*/
const initImageStyles = () => {
// 组件挂载时处理
onMounted(() => {
processImageStyles()
})
// 监听内容变化
if (typeof contentRef === 'function') {
// 如果是函数,直接监听
watch(contentRef, () => {
processImageStyles()
}, {deep: true})
} else {
// 如果是 Ref监听其值
watch(contentRef, () => {
processImageStyles()
}, {deep: true})
}
}
return {
forceImageStyles,
processImageStyles,
initImageStyles,
2025-10-13 14:50:45 +08:00
2025-10-13 13:51:40 +08:00
}
}