如何在 Vue 3 + Pinia 中管理多个图表的展示状态?

我希望实现这样一个功能

  • 分成两部分

    • 图表显示和切换控制区域
    • 图表描述信息展示区域
  • 点击上下按钮在同类图表中切换,切换的形式为上下切换,对应描述也跟着变
  • 点击左右按钮在不同类中切换,切换的形式为左右切换,对应描述也跟着变

大体像这样(图表描述信息展示区域没有)
image.png

数据描述如下:

const config = [
  {
    title: "柱状图学习",
    kinds: [
      {
        title: "简单柱状图",
        id: "0-0",
        component: BarSimple
      },
      {
        title: "复杂柱状图",
        id: "0-1",
        component: BarSimple
      }
    ]
  },
  {
    title: "折线图学习",
    kinds: [
      {
        title: "简单折线图",
        id: "1-0",
        component: BarSimple
      },
      {
        title: "复杂折线图",
        id: "1-1",
        component: BarSimple
      }
    ]
  }
]

我想使用pinia来管理当前展示的图表。

  • 每一个图表描述信息都包含一个唯一的id,我就用这个id来标识当前的图表。

问题:
但是我这里的状态依赖于从@/components/EchartsShow/config.js导入的config,如果我想建立一个新的状态管理依赖于其他的config,那怎么办?再复制一遍,改一下import config from "@/components/EchartsShow/config.js"

import {defineStore} from 'pinia'
import { computed, ref } from 'vue'
import config from "@/components/EchartsShow/config.js"

export const useChartStore = defineStore('chart', () => {
  const currentShowChart = ref("0-0");

  const currentShowChartInfo = computed(() => {
    const info = {title: "", subtitle: "", description: ""};
    const cf = config.find(item => item.kinds.some(kd => kd.id === currentShowChart.value));
    if(!cf) return info;
    info.title = cf.title;
    const kd = cf.kinds.find(item => item.id === currentShowChart.value);
    info.subtitle = kd.title;
    info.description = kd.description;
    return info;
  })

  const scrollTo = (direction) => {
    let [x, y] = currentShowChart.value.split("-").map(e => Number(e));
    if(direction === 'top')  {
      if(y !== 0) --y;
    }else if(direction === 'bottom') {
      if(y !== config[x].kinds.length - 1) ++y;
    }else if(direction === 'left') {
      if(x !== 0) --x;
    }else if(direction === 'right') {
      if(x !== config.length - 1) ++x;
    }
    const newId = `${x}-${y}`;
    document.getElementById(newId).scrollIntoView({
      behavior: "smooth"
    })
    currentShowChart.value = newId;
  }

  return {currentShowChart, scrollTo,currentShowChartInfo};
})

附:

阅读 1.5k
2 个回答

看你这需求应该用不上Pinia。再展示组件里定义两个数组,一个上下切换的数据数组,一个左右切换的数据数组。

如果一定要使用Pinia,可以把页面的两个数组,定义到Pinia里。

新状态管理依赖于其他的config,只能重新引入其他的config.js状态元数据了,没其他方法。

或者在components/EchartsShow目录下面新建一个config文件夹,里面新建index.js文件,index.js文件中使用具名导出,分别导出config1、config2,后面新建状态管理可以直接导入
import {config1, config2} from "@/components/EchartsShow/config"

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题