vue实现文字云
Vue 实现文字云
安装依赖
需要安装 wordcloud 或 echarts-wordcloud 插件,推荐使用 echarts-wordcloud,因为它基于 ECharts,功能更强大且易于集成。
npm install echarts echarts-wordcloud
基础实现
在 Vue 组件中引入 ECharts 和 WordCloud 扩展,创建一个文字云图表。
<template>
<div ref="wordcloudChart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
import 'echarts-wordcloud';
export default {
mounted() {
this.initWordCloud();
},
methods: {
initWordCloud() {
const chart = echarts.init(this.$refs.wordcloudChart);
const option = {
series: [{
type: 'wordCloud',
shape: 'circle',
left: 'center',
top: 'center',
width: '80%',
height: '80%',
right: null,
bottom: null,
sizeRange: [12, 60],
rotationRange: [-45, 45],
rotationStep: 15,
gridSize: 8,
drawOutOfBound: false,
textStyle: {
fontFamily: 'sans-serif',
fontWeight: 'bold',
color: function () {
return 'rgb(' + [
Math.round(Math.random() * 160 + 95),
Math.round(Math.random() * 160 + 95),
Math.round(Math.random() * 160 + 95)
].join(',') + ')';
}
},
data: [
{ value: 90, name: 'Vue' },
{ value: 80, name: 'React' },
{ value: 70, name: 'JavaScript' },
{ value: 60, name: 'TypeScript' },
{ value: 50, name: 'HTML' },
{ value: 40, name: 'CSS' },
{ value: 30, name: 'Node.js' },
{ value: 20, name: 'Webpack' }
]
}]
};
chart.setOption(option);
window.addEventListener('resize', chart.resize);
}
}
};
</script>
动态数据绑定
可以通过 props 或 API 请求动态加载数据。
<script>
export default {
props: {
wordData: {
type: Array,
default: () => []
}
},
watch: {
wordData: {
handler(newVal) {
if (newVal.length) {
this.updateWordCloud(newVal);
}
},
immediate: true
}
},
methods: {
updateWordCloud(data) {
const chart = echarts.init(this.$refs.wordcloudChart);
chart.setOption({
series: [{
type: 'wordCloud',
data: data
}]
});
}
}
};
</script>
自定义样式与交互
可以调整文字云的形状、颜色和添加点击事件。
<script>
methods: {
initWordCloud() {
const chart = echarts.init(this.$refs.wordcloudChart);
chart.on('click', (params) => {
console.log('点击了:', params.name);
});
chart.setOption({
series: [{
type: 'wordCloud',
shape: 'diamond',
textStyle: {
color: function (params) {
const colors = ['#c23531', '#2f4554', '#61a0a8', '#d48265'];
return colors[params.dataIndex % colors.length];
}
}
}]
});
}
}
</script>
响应式调整
在窗口大小变化时重新渲染文字云。
<script>
mounted() {
this.initWordCloud();
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
if (this.$refs.wordcloudChart) {
echarts.init(this.$refs.wordcloudChart).resize();
}
}
}
</script>
注意事项
- 数据格式要求为
{ name: string, value: number }的数组,value决定文字大小。 - 文字云性能受数据量影响,建议限制数据条目(如 50-100 条)。
- 在 SSR(如 Nuxt.js)中使用时需动态导入 ECharts,避免服务端渲染报错。







