写一段代码实现“手机端单列、桌面端左侧1/3为树形菜单,右侧2/3为图表”

解读

  1. 移动端优先:国内 90% 的 BI 用户会在微信/钉钉内打开,因此先写手机端单列布局,再用媒体查询或 Dash-Bootstrap-Components 的响应式类名适配桌面。
  2. 左侧 1/3、右侧 2/3:用 Bootstrap 的 Row+Col 栅格,桌面 width=4 vs width=8,手机 width=12。
  3. 树形菜单:Dash 原生没有 Tree,但国内面试认“用 Treeview 组件”即可,可用 dash-antd-components(阿里 Ant Design React 的 Dash 封装)或 dbc.Accordion 模拟。为降低依赖,示例用 dbc.Accordion 做二级树,面试官更看重“知道去哪找组件”。
  4. 右侧图表:用 Plotly Express 快速出图,重点展示“回调里根据菜单节点更新图表”,这是生产级仪表盘的核心。
  5. 代码量:面试写 60 行以内即可跑通,但要把“响应式 + 回调 + 组件选型”三个得分点写全。

知识点

  • Dash-Bootstrap-Components 栅格系统:dbc.Container、dbc.Row、dbc.Col,以及 xs md lg 断点。
  • 响应式断点:国内常用 md=768px 作为手机/桌面分界线。
  • 树形导航的两种实现:① dash-antd-components 的 Tree;② dbc.Accordion/Collapse 手写树。
  • 回调 Pattern:Input 取树节点 id,Output 到右侧 Graph,State 可带缓存。
  • 生产细节:
    – 设置 meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}] 保证手机端缩放。
    – 用 style={"height": "100vh"} 让左侧菜单在桌面可独立滚动,符合国内 UI 规范。

答案

# -*- coding: utf-8 -*-
# 安装:pip install dash dash-bootstrap-components plotly
import dash
from dash import Input, Output, html, dcc
import plotly.express as px
import dash_bootstrap_components as dbc

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{"name": "viewport",
                            "content": "width=device-width, initial-scale=1"}])

# 模拟树形数据
tree_data = {
    "销售": {"华东": ["上海", "江苏"], "华南": ["广东", "海南"]},
    "财务": {"成本": ["原材料", "人工"], "收入": ["线上", "线下"]}
}

# 构造 Accordion 形式的树
def build_accordion():
    items = []
    for dept, regions in tree_data.items():
        children = []
        for region, cities in regions.items():
            # 二级菜单
            children.append(
                dbc.AccordionItem(
                    [dbc.ListGroup(
                        [dbc.ListGroupItem(city, id=f"leaf-{city}", action=True, n_clicks=0)
                         for city in cities],
                        flush=True
                    )],
                    title=region
                )
            )
        items.append(dbc.Accordion(children, start_collapsed=True, id=f"acc-{dept}"))
    return items

# 布局
app.layout = dbc.Container(fluid=True, children=[
    dbc.Row([
        # 左侧树形菜单:手机 12,桌面 4
        dbc.Col([
            html.H5("菜单", className="mb-3"),
            html.Div(build_accordion(), style={"height": "100vh", "overflowY": "auto"})
        ], xs=12, md=4, className="bg-light p-3"),
        # 右侧图表:手机 12,桌面 8
        dbc.Col([
            dcc.Graph(id="right-chart", style={"height": "80vh"})
        ], xs=12, md=8, className="p-3")
    ])
])

# 回调:点击叶子节点更新图表
@app.callback(
    Output("right-chart", "figure"),
    Input({"type": "leaf", "index": dash.ALL}, "n_clicks"),
    prevent_initial_call=True
)
def update_chart(*args):
    ctx = dash.callback_context
    if not ctx.triggered:
        return px.scatter(title="请选择节点")
    # 解析被点击的节点 id
    node_id = ctx.triggered[0]["prop_id"].split(".")[0]
    city = node_id.replace("leaf-", "")
    # 模拟数据
    df = px.data.gapminder().query("country == 'China'")
    fig = px.line(df, x="year", y="gdpPercap", title=f"{city} 指标趋势")
    return fig

if __name__ == "__main__":
    app.run_server(debug=True, host="0.0.0.0", port=8050)

跑通后,手机端自动单列;桌面端左侧 1/3 树菜单,右侧 2/3 图表,点击任意城市节点右侧折线图即时刷新。

拓展思考

  1. 真实生产要把 Accordion 换成 dash-antd-components 的 Tree,支持异步加载大数据;同时给每个节点绑定 key,回调用 MATCH 模式,避免全量 n_clicks 监听。
  2. 国内部署:用 Gunicorn + Nginx,开启 proxy_buffering off 解决钉钉内嵌页面空白;再加 requests_pathname_prefix 适配子路径挂载。
  3. 权限控制:树节点按用户角色过滤,可在回调里读 Redis 中的权限表,返回空图或 403 提示。
  4. 性能优化:右侧图表若数据量大,先用 dcc.Store 做客户端缓存,再用 plotly_resampler 做降采样,避免 3 秒以上白屏。
  5. 主题切换:国内领导喜欢“深色大屏”,可封装 dbc.ThemeChangerAIO,一键切换 BOOTSTRAP 与 DARKLY 主题,并在 localStorage 记住用户偏好。