You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Firebase获取数据展示在卡片上,点击后跳转详情页加载对应数据

Firebase卡片列表+详情页跳转实现方案

前置配置

  • 首先在Firebase控制台开通数据库服务,推荐使用Cloud Firestore,以下示例均基于Firestore编写
  • 前端项目引入并初始化Firebase SDK,调试阶段可先将数据库权限临时开放为可读,规则示例:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if true;
      allow write: if request.auth != null;
    }
  }
}

注意:生产环境务必修改权限规则,避免数据泄露

卡片列表页实现

页面核心逻辑是拉取列表精简字段、渲染卡片、绑定跳转参数:

  1. 页面加载时调用Firebase查询接口,仅拉取卡片需要展示的字段(标题、简介、缩略图、文档ID),减少请求体积
  2. 遍历返回的数据集渲染为卡片列表,每个卡片绑定对应数据的唯一documentId作为跳转传参
  3. 监听卡片点击事件,跳转时将documentId带入详情页的路由参数
    原生JS代码示例:
import { getFirestore, collection, getDocs } from "firebase/firestore";
const db = getFirestore();
const cardContainer = document.querySelector('#card-container');

async function loadCardList() {
  const listSnapshot = await getDocs(collection(db, "你的业务集合名"));
  listSnapshot.forEach(doc => {
    const item = doc.data();
    const card = document.createElement('div');
    card.className = 'card-item';
    // 填充卡片内容
    card.innerHTML = `
      <img src="${item.cover}" alt="${item.title}">
      <h3>${item.title}</h3>
      <p class="brief">${item.briefIntro}</p>
    `;
    // 绑定跳转事件
    card.addEventListener('click', () => {
      window.location.href = `detail.html?docId=${doc.id}`;
    });
    cardContainer.appendChild(card);
  });
}

// 页面加载后触发数据拉取
window.onload = loadCardList;

如果使用前端框架,路由传参可以替换为框架自带方法:

  • Vue:this.$router.push({ path: '/detail', query: { id: doc.id } })
  • React:navigate('/detail', { state: { id: doc.id } })

详情页实现

页面核心逻辑是读取路由参数、拉取对应单条全量数据、渲染详情:

  1. 页面加载后先解析路由中携带的documentId参数,参数为空直接返回列表页
  2. 调用Firebase单条文档查询接口,拉取该ID对应的全量业务数据
  3. 将返回的全量字段按需渲染到详情页对应位置
    原生JS代码示例:
import { getFirestore, doc, getDoc } from "firebase/firestore";
const db = getFirestore();

async function loadDetailData() {
  // 解析路由参数
  const params = new URLSearchParams(window.location.search);
  const docId = params.get('docId');
  if(!docId) {
    alert('参数无效,请返回列表页');
    window.location.href = 'list.html';
    return;
  }
  // 查询单条全量数据
  const docRef = doc(db, "你的业务集合名", docId);
  const docSnapshot = await getDoc(docRef);
  if(docSnapshot.exists()) {
    const fullData = docSnapshot.data();
    // 按需渲染全量字段
    document.querySelector('#detail-title').innerText = fullData.title;
    document.querySelector('#detail-cover').src = fullData.cover;
    document.querySelector('#detail-content').innerHTML = fullData.fullContent;
    document.querySelector('#publish-time').innerText = fullData.publishTime;
  } else {
    alert('当前数据不存在');
  }
}

window.onload = loadDetailData;

界面参考

  • 列表页:卡片采用流式布局,单张卡片包含缩略图、标题、简短简介,点击整张卡片均可触发跳转
  • 详情页:顶部展示大标题和发布时间,下方按排版展示全量正文和关联配图,适配移动端滚动浏览

内容的提问来源于stack exchange,提问作者WHO am I

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:39:04