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

实现WooCommerce分类菜单可折叠功能求助

实现WooCommerce分类菜单可折叠功能(Vue版)

针对你的需求,用Vue的响应式状态来实现会比jQuery更贴合现有代码逻辑,以下是修改方案:

步骤1:添加响应式状态

在你的Vue组件data中新增变量,记录当前展开的父分类ID:

data() {
  return {
    // 保留原有数据...
    expandedCategoryId: null // 初始默认不展开任何父分类
  }
}

步骤2:修改模板代码

调整父分类交互逻辑,添加点击切换展开状态的事件,同时控制子分类的显示:

<!-- Categories Start -->
<h6>Categories</h6>

<div class="categories">
  <label class="category-filter" :key="'category_all'">
    <input type="radio" name="category" v-model="category" value="" v-on:change="resetPagination();triggerFilter();" />
    <span>All Products</span>
    <!-- <span class="count" v-html="pagination.total_posts"></span> -->
  </label>

  <div class="category-filter" v-for="categorySingle in categories" :key="'category_' + categorySingle.id">
    <div v-if="categorySingle.parent == 0">
      <!-- 父分类区域,添加点击事件切换展开状态 -->
      <div @click="toggleCategory(categorySingle.id)" class="parent-category">
        <label>
          <input type="radio" name="category" v-model="category" :value="categorySingle.id" v-on:change="resetPagination();triggerFilter();" />
          <span v-html="categorySingle.name"></span>
          <span class="count" v-html="categorySingle.count"></span>
          <!-- 可选:添加展开/折叠图标 -->
          <span class="expand-icon">{{ expandedCategoryId === categorySingle.id ? '▼' : '▶' }}</span>
        </label>
      </div>

      <!-- 子分类区域,仅当前父分类展开时显示 -->
      <div 
        v-for="categoryChild in categories" 
        :key="'child_category_' + categoryChild.id" 
        v-if="categoryChild.parent == categorySingle.id && expandedCategoryId === categorySingle.id"
      >
        <label class="ms-4 mt-2 d-block position-relative">
          <input type="radio" name="category" v-model="category" :value="categoryChild.id" v-on:change="resetPagination();triggerFilter();" />
          <span v-html="categoryChild.name"></span>
          <span class="count" v-html="categoryChild.count"></span>
        </label>
      </div>
    </div>
  </div>
</div>
<!-- Categories End -->

步骤3:添加切换方法

在组件methods中新增切换展开状态的函数:

methods: {
  // 保留原有方法...
  toggleCategory(id) {
    // 点击当前展开的分类则折叠,否则展开该分类
    this.expandedCategoryId = this.expandedCategoryId === id ? null : id;
  }
}

可选:CSS优化

给父分类添加上手型光标和图标样式,提升交互体验:

.parent-category {
  cursor: pointer;
}
.expand-icon {
  margin-left: 8px;
  font-size: 12px;
}

关键说明

  • 用Vue响应式变量expandedCategoryId控制子分类显示,完全贴合现有Vue代码逻辑,避免jQuery操作DOM的冲突。
  • 若需要支持同时展开多个父分类,可将expandedCategoryId改为数组,修改toggleCategory方法实现ID的添加/移除,子分类判断条件改为expandedCategoryIds.includes(categorySingle.id)即可。

内容的提问来源于stack exchange,提问作者Ray_86694

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:23:13