当前位置: 首页 > 知识库问答 >
问题:

vue.js - vue3 怎么更新 echarts?

上官鸿朗
2023-08-02

需求,我的 vue3 中的 data=ref([]) 更新之后,我希望 echarts 的图标也跟着一起更新

但是目前不会,我该怎么修改

<template>    <top-bar></top-bar>    <div class="container">        <a-page-header style="border: 1px solid rgb(235, 237, 240)" title="匹配结果入库" sub-title="查看匹配结果入库情况"            @back="navigateToRoot">            <a-row class="content">                <div style="flex: 1">                    <br />                    <div>                        在该页面,可以查看以下信息:                        <br />                        <br />                        <ul>                            <li>指定公司维度的产出</li>                            <li>指定平台维度的产出</li>                            <li>指定母本的产出</li>                        </ul>                    </div>                </div>            </a-row>        </a-page-header>    </div>    <div class="container">        <div class="container-item">            <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">                <a-form-item label="meta_uuid">                    <a-input v-model:value="formState.meta_uuid" placeholder="根据 meta_uuid 筛选,可以不填" />                </a-form-item>                <a-form-item label="company_id">                    <a-form-item name="input-number" no-style>                        <a-input-number v-model:value="formState['company_id']" placeholder="根据 company_id 筛选,可以不填" />                    </a-form-item>                    <span class="ant-form-text">根据 company_id 筛选,可以不填</span><a href="/company_list"                        target="_blank">查看公司列表</a>                </a-form-item>                <a-form-item label="track_source_id">                    <a-form-item name="input-number" no-style>                        <a-input-number v-model:value="formState['track_source_id']" placeholder="请输入 track_source_id" />                    </a-form-item>                    <span class="ant-form-text">指定 track_source_id <a href="/search_engine_health_check"                            target="_blank">[详情]</a></span>                </a-form-item>                <a-form-item label="last_day">                    <a-form-item name="input-number" no-style>                        <a-input-number v-model:value="formState['last_day']" placeholder="查看最近多少天" />                    </a-form-item>                    <span class="ant-form-text"> 查看最近多少天</span>                </a-form-item>                <a-form-item label="选择资源类型">                    <a-form-item name="input-number" no-style>                        <!-- <a-input-number v-model:value="formState['source_type']" placeholder="根据 source_type 筛选,可以不填" /> -->                        <a-radio-group v-model:value="formState.source_type">                            <a-radio value="image">image</a-radio>                            <a-radio value="text">text</a-radio>                        </a-radio-group>                    </a-form-item>                    <!-- <span class="ant-form-text">选择资源类型:image 或者 text</span> -->                </a-form-item>                <a-form-item label="match 状态">                    <a-form-item name="input-number" no-style>                        <!-- <a-input-number v-model:value="formState['classify']" placeholder="根据 source_type 筛选,可以不填" /> -->                        <a-radio-group v-model:value="formState.classify">                            <a-radio value="all">所有</a-radio>                            <a-radio value="unclassify">疑似侵权</a-radio>                            <a-radio value="infringement">确认侵权</a-radio>                        </a-radio-group>                    </a-form-item>                    <!-- <span class="ant-form-text">选择全部还是疑似侵权</span> -->                </a-form-item>                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">                    <a-button type="primary" :loading="searchLoading" @click="sendRequest">                        提交                    </a-button>                    <span style="margin-left: 25px"></span>                    <a-button @click="clearForm">清空</a-button>                </a-form-item>            </a-form>        </div>    </div>    <div class="container">        <div class="container-item">            <a-typography-title :level="5"> 每个入库情况:            </a-typography-title>            <div ref="chartRefText" class="chart"></div>            <button @click="toggleLegend">一键反选图例</button>        </div>    </div></template>  <script setup>import axios from "axios";import { ref, onMounted, reactive, watch } from "vue";import * as echarts from "echarts";import { useRouter, useRoute } from "vue-router";const chartRefText = ref(null);let myChartText;const data = ref([]);const searchLoading = ref(false);const labelCol = {    style: {        width: "150px",    },};const wrapperCol = {    span: 14,};const route = useRoute();const formState = reactive({    keyword_task_id: route.query.keyword_task_id || null,    meta_uuid: route.query.meta_uuid || null,    company_id: route.query.company_id || null,    last_day: route.query.last_day || 7,    track_source_id: route.query.track_source_id || null,    classify: route.query.classify || 'all',    source_type: route.query.source_type || 'image',});onMounted(async () => {    myChartText = echarts.init(chartRefText.value);    try {        const xAxisData = data.value.map(item => item.source_date);        const yAxisData = data.value.map(item => item.source_count);        const option = {            xAxis: {                type: 'category',                data: xAxisData            },            yAxis: {                type: 'value'            },            series: [{                type: 'line',                data: yAxisData            }]        };        myChartText.setOption(option);    } catch (error) {        console.error(error);    }});watch(async () => {    myChartText = echarts.init(chartRefText.value);    try {        const xAxisData = data.value.map(item => item.source_date);        const yAxisData = data.value.map(item => item.source_count);        const option = {            xAxis: {                type: 'category',                data: xAxisData            },            yAxis: {                type: 'value'            },            series: [{                type: 'line',                data: yAxisData            }]        };        myChartText.setOption(option);    } catch (error) {        console.error(error);    }});const clearForm = () => {    for (const key in formState) {        if (Reflect.has(formState, key)) {            formState[key] = null;        }    }    formState["limit"] = 20;    const urlParams = new URLSearchParams();    for (const key in formState) {        if (Reflect.has(formState, key)) {            if (formState[key] === "") {                formState[key] = null;            }            if (formState[key] !== null) {                urlParams.set(key, formState[key]);            }        }    }    window.history.replaceState(null, null, `?${urlParams.toString()}`);};const sendRequest = () => {    const urlParams = new URLSearchParams();    for (const key in formState) {        if (Reflect.has(formState, key)) {            if (formState[key] === "") {                formState[key] = null;            }            if (formState[key] !== null) {                urlParams.set(key, formState[key]);            }        }    }    window.history.replaceState(null, null, `?${urlParams.toString()}`);    searchLoading.value = true;    const queryParams = {};    for (const key in formState) {        if (Reflect.has(formState, key)) {            if (formState[key] !== null) {                queryParams[key] = formState[key];            }        }    }    const url =        "http://meta-console-api.mediawise.vobile.cn/match/count";    axios        .get(url, {            params: queryParams,        })        .then((response) => {            data.value = response.data;        })        .catch((error) => {            console.error(error);        })        .finally(() => {            searchLoading.value = false;        });};const toggleLegend = () => {    const { legend } = myChartText.getOption() || {}; // Ensure legend is defined    const { selected } = legend || {};    const newSelected = {};    Object.keys(selected || {}).forEach((key) => {        newSelected[key] = !selected[key];    });    myChartText.setOption({        legend: {            selected: newSelected,        },    });};</script>  <style scoped>.chart-container {    width: 100%;    max-width: 1440px;    margin: 0 auto;}.chart {    width: 100%;    height: 400px;}</style>

共有1个答案

闻人举
2023-08-02

首先,确保在你的项目中已安装 ECharts:
bash
Copy code
npm install echarts
在组件中引入 ECharts:
javascript
Copy code
import * as echarts from 'echarts';
在需要渲染 ECharts 图表的元素上添加 ref:
html
Copy code
<template>
<div>

<div ref="echartsContainer" style="height: 300px;"></div>

</div>
</template>
在组件的 setup 函数中创建一个响应式的 ECharts 实例的 ref:
javascript
Copy code
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

export default {
setup() {

const echartsInstance = ref(null);// 组件挂载时初始化 EChartsonMounted(() => {  const container = document.getElementById('echartsContainer');  echartsInstance.value = echarts.init(container);  // 在此处也可以设置初始图表数据  // 例如:  // const initialChartData = [...];  // echartsInstance.value.setOption({  //   series: [  //     {  //       data: initialChartData,  //       // 其他系列配置...  //     },  //   ],  // });});// 组件卸载时销毁 ECharts 实例onUnmounted(() => {  if (echartsInstance.value) {    echartsInstance.value.dispose();  }});return { echartsInstance };

},
};
现在,你需要监视 ref 数据的变化,并相应地更新 ECharts 图表。你可以使用 watcher 来实现:
javascript
Copy code
import { watch } from 'vue';

export default {
setup() {

// ... (前面的 setup 代码)watch(  () => yourRefData.value, // 将 'yourRefData' 替换为实际的 ref 数据名称  (newData) => {    if (echartsInstance.value) {      // 在此处更新 ECharts 数据,使用 'setOption' 方法      // 例如:      // const chartData = newData.map(item => item.value);      // echartsInstance.value.setOption({      //   series: [      //     {      //       data: chartData,      //       // 其他系列配置...      //     },      //   ],      // });    }  });// ... (其他代码)

},
};
请将 'yourRefData' 替换为你实际使用的包含要在 ECharts 中使用的数据的 ref 名称。在 watcher 中,你可以从 ref 中提取必要的数据,并使用 setOption 方法来更新 ECharts 图表。watch 函数将在 ref 数据变化时触发更新。

 类似资料: