1,安装
npm install element-resize-detector --save
2,引入使用,这里以echarts为例
<template>
<div class="hello">
<div class="canvas" ref="canvas"></div>
</div>
</template>
<script>
import * as echarts from "echarts";
export default {
name: "HelloWorld",
data() {
return {
chart: null,
};
},
mounted() {
this.initCanvas();
},
methods: {
initCanvas() {
this.chart = echarts.init(this.$refs.canvas);
this.showPie();
},
resize() {
this.$nextTick(() => {
this.chart.resize();
});
},
showPie() {
this.chart.setOption({
series: [
{
name: "访问来源",
type: "pie", // 设置图表类型为饼图
radius: "55%", // 饼图的半径,外半径为可视区尺寸(容器高宽中较小一项)的 55% 长度。
data: [
// 数据数组,name 为数据项名称,value 为数据项值
{ value: 235, name: "视频广告" },
{ value: 274, name: "联盟广告" },
{ value: 310, name: "邮件营销" },
{ value: 335, name: "直接访问" },
{ value: 400, name: "搜索引擎" },
],
},
],
});
this.chart.resize();
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
width: 100%;
height: 300px;
}
.canvas {
width: 100%;
height: 100%;
}
</style>
注意:如果只是使用echarts自带的resize(),在页面刷新的时候会自适应
3,引入使用,使用了就可以实时根据窗口大小实时变化了
import elementResizeDetectorMaker from "element-resize-detector";
const erd = elementResizeDetectorMaker();
erd.listenTo(this.$el, this.resize.bind(this));
<template>
<div class="hello">
<div class="canvas" ref="canvas"></div>
</div>
</template>
<script>
import * as echarts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";
const erd = elementResizeDetectorMaker();
export default {
name: "HelloWorld",
data() {
return {
chart: null,
};
},
mounted() {
this.initCanvas();
},
methods: {
initCanvas() {
this.chart = echarts.init(this.$refs.canvas);
this.showPie();
},
resize() {
this.$nextTick(() => {
this.chart.resize();
});
},
showPie() {
this.chart.setOption({
series: [
{
name: "访问来源",
type: "pie", // 设置图表类型为饼图
radius: "55%", // 饼图的半径,外半径为可视区尺寸(容器高宽中较小一项)的 55% 长度。
data: [
// 数据数组,name 为数据项名称,value 为数据项值
{ value: 235, name: "视频广告" },
{ value: 274, name: "联盟广告" },
{ value: 310, name: "邮件营销" },
{ value: 335, name: "直接访问" },
{ value: 400, name: "搜索引擎" },
],
},
],
});
erd.listenTo(this.$el, this.resize.bind(this));
},
},
destroyed() {
erd.uninstall(this.$refs.canvas);
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
width: 100%;
height: 300px;
}
.canvas {
width: 100%;
height: 100%;
}
</style>
注意:使用的时候listen了,适用完毕需要remove掉