想更多的了解如何父级页面调用子组件的方法吗?在提高前端技术吗?想更好的提升工作效率吗?可以看看这篇文章,希望能给你带来收获。
实现场景
点击展示词云,然后整个页面通过echarts渲染词云页面。主要是在父级页面上调用组件内的方法。
设计方案
首先,搭建词云组件,注意其中组件内的方法需要暴露出来,父级组件才能访问到。组件文件名为 WordsListThree.vue
其次,父级页面直接调用。
代码实施
词云组件的代码如下:
<template>
<div class="page">
<div ref="chinaMap" class="echart-china">
</div>
</div>
</template>
<script lang="ts" setup >
import * as echarts from 'echarts'
import 'echarts-wordcloud';
import { onMounted, ref } from 'vue'
import { reactive } from 'vue'
const chinaMap = ref()
const list = [
{
value: '50',
name: '数字人骨骼动作',
textStyle: {
shadowBlur: 1,
shadowColor: '#A886F6',
shadowOffsetY: 0,
shadowOffsetX: 0,
color: '#A886F6',
},
}, // 50
]
function drawChina() {
let myChart = echarts.init(chinaMap.value)
let option = {
tooltip: {
show: true,
borderColor: '#fe9a8bb3',
borderWidth: 1,
padding: [10, 15, 10, 15],
confine: true,
backgroundColor: 'rgba(255, 255, 255, .9)',
textStyle: {
color: 'hotpink',
lineHeight: 22
},
extraCssText: 'box-shadow: 0 4px 20px -4px rgba(199, 206, 215, .7);border-radius: 4px;'
},
series: [
{
type: 'wordCloud',
shape: 'circle',
left: 'center',
top: 'center',
width: '100%',
height: '100%',
right: null,
bottom: null,
sizeRange: [14, 50],
rotationRange: [0, 0],
rotationStep: 0,
gridSize: 25,
drawOutOfBound: false,
layoutAnimation: true,
textStyle: {
fontFamily: 'PingFangSC-Semibold',
fontWeight: 600,
color: function (params) {
let colors = ['#fe9a8bb3', '#fe9a8bb3', '#fe9a8b03', '#9E87FFb3', '#9E87FFb3', '#9E87FFb3', '#fe9a8bb3', '#fe9a8bb3', '#fe9a8bb3', '#73DDFF', '#58D5FF']
return colors[parseInt(Math.random() * 10)];
},
},
emphasis: {
focus: 'none',
},
data: list,
},
],
};
myChart.setOption(option)
}
//暴露组件内的方法,供父级页面调用
defineExpose({
drawChina
})
</script>
<style lang="less" scoped>
.page {
width: 100%;
height: 400px;
color: #fff;
background-position: center center;
background-size: cover;
}
.echart-china {
height: 100%;
width: 100%;
/* border: 1px solid; */
}
</style>
父级页面的代码如下:
<script setup>
import { ref } from 'vue';
import WordsListThree from '../components/WordsListThree.vue';
const myWords = ref(null)
const showCase = (index) => {
myWords.value.drawChina()
}
</script>
<template>
<main>
<div class="content-3d-button" @click="showCase()">显示组件</div>
<WordsListThree ref="myWords"></WordsListThree>
</main>
</template>
<style scoped lang="less">
.content-3d-button{
display: block;
width: 400px;
margin: 0 auto;
text-align: center;
font-size: 60px;
border: 1px solid;
}
</style>
最后展示的结果如下:
收获总结
直接将组件实例化,然后将组件中的方法暴露出来,这种用起来非常方便。在父级元素传递给子级元素的过程中,更方便,技能更熟练,省时间。
写这篇调用子组件内的文章是想要将梳理自身的知识经验,同时对内进行复盘,让自己在工作之余有所收获,而不是做了很多的项目,当其他人询问技术使用了哪些东西,自己回答不上来,同时也让自己明天,今天的工作有结果,有收获。
努力提高前端技术的小伙伴,别忘了点赞+收藏哟!