第一步:封装自定义指令
在directive文件夹下创建一个resizeObserver.js文件
内容如下
// 监听元素大小变化的指令
const map = new WeakMap()
const ob = new ResizeObserver((entries) => {
for (const entry of entries) {
// 获取dom元素的回调
const handler = map.get(entry.target)
//存在回调函数
if (handler) {
// 将监听的值给回调函数
handler({
width: entry.borderBoxSize[0].inlineSize,
height: entry.borderBoxSize[0].blockSize
})
}
}
})
export const Resize = {
mounted(el, binding) {
//将dom与回调的关系塞入map
map.set(el, binding.value)
//监听el元素的变化
ob.observe(el)
},
unmounted(el) {
//取消监听
ob.unobserve(el)
}
}
export default Resize
第二步:在directive文件夹再创建一个index.js文件,目的是为了集中注册自定义指令
import { Resize } from "./resizeObserver"
export default function directive(app){
app.directive('Resize', Resize)
}
第三步:在main.js文件进行全局注册
import directives from "@/util/directive/index"
app.use(directives)
第四步:使用方法
<template>
<div class="charts">
<div ref="chartbar" class="sample_chart" v-resize="onResize"></div>
</div>
</template>
<script setup>
// 自适应
const onResize = () => {
const myChartBar = echarts.init(chartbar.value);
myChartBar.resize();
}
</script>