1.在.js文件中编写自定义指令
export default {
install(Vue) {
Vue.directive('resizable', {
bind(el, binding) {
const minWidth = binding.value.minWidth || MIN_WIDTH;
const maxWidth = binding.value.maxWidth || MAX_WIDTH;
const defaultHeight = binding.value.defaultHeight || DEFAULT_HEIGHT;
const minHeight = binding.value.minHeight || MIN_HEIGHT;
const maxHeight = binding.value.maxHeight || MAX_HEIGHT;
const heightRange = maxHeight - minHeight;
const widthRange = maxWidth - minWidth;
const styles = {
width: binding.value.width || DEFAULT_WIDTH,
height: binding.value.height || defaultHeight,
};
el.style.width = styles.width;
el.style.height = styles.height;
window.addEventListener('resize', handleResize);
handleResize();
function handleResize() {
const screenWidth = window.innerWidth;
if (screenWidth >= maxWidth) {
styles.height = `${maxHeight}px`;
} else if (screenWidth < minWidth) {
styles.height = `${minHeight}px`;
} else {
const baseRatio = (el.offsetWidth - minWidth) / widthRange;
const baseHeightDiff = Math.round(baseRatio * heightRange);
const ratio = (screenWidth - el.offsetWidth) / widthRange;
const heightDiff = Math.round(ratio * heightRange);
styles.height = `${minHeight + baseHeightDiff + heightDiff}px`;
}
el.style.height = styles.height;
}
},
unbind() {
window.removeEventListener('resize', handleResize);
},
});
},
}
2.在main.js文件中全局注册
import grid from '@/utils/grid.js'
Vue.use(grid)
3.在.vue文件中使用
<div class="img-bg"
v-resizable="{ width: '100%', height: '300px', maxHeight: 400, minHeight: 200, minWidth: 600, maxWidth: 1500, defaultHeight: '400px'}">
</div>