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

如何获取tree-select的所有选项并将其存入列表?

解决Cypress获取vue-treeselect所有选项的问题

你之前的代码只能获取已选中选项,主要有两个原因:

  1. 选择器.vue-treeselect__single-value本身就是用来展示已选中值的元素,并非下拉菜单里的所有选项。
  2. vue-treeselect的下拉菜单是动态挂载到<body>下的独立容器,不属于原组件元素的子节点,所以用.find()无法定位到它。

基础解决方案(一次性渲染所有选项)

先点击展开下拉菜单,直接定位到下拉菜单容器,再获取所有选项元素:

const groups = dropdownMenuSelector[1].options[languageStrings]

// 点击展开下拉菜单
cy.get('.vue-treeselect.vue-treeselect--single')
  .find('div.vue-treeselect__control-arrow-container')
  .click()

// 等待下拉菜单可见,确保选项已渲染
cy.get('.vue-treeselect__menu')
  .should('be.visible')
  // 获取所有选项(包括树形结构的子选项)
  .find('.vue-treeselect__option')
  .then(options => {
    // 提取所有选项文本并去空
    const optionTexts = [...options].map(option => option.innerText.trim())
    // 将所有文本添加到目标数组
    groups.push(...optionTexts)
  })

cy.log(groups)

处理滚动加载的选项(选项过多时动态渲染)

如果下拉选项是滚动加载的(滚动到底部才渲染新选项),需要递归滚动直到所有选项加载完成:

const groups = dropdownMenuSelector[1].options[languageStrings]

// 点击展开下拉菜单
cy.get('.vue-treeselect.vue-treeselect--single')
  .find('div.vue-treeselect__control-arrow-container')
  .click()

// 递归滚动获取所有选项
const getAllOptions = () => {
  cy.get('.vue-treeselect__menu')
    .then($menu => {
      const currentOptionCount = $menu.find('.vue-treeselect__option').length
      // 滚动到菜单底部
      $menu.scrollTop($menu[0].scrollHeight)
      
      // 等待新选项加载
      cy.wait(500)
      cy.get('.vue-treeselect__menu')
        .then($updatedMenu => {
          const updatedOptionCount = $updatedMenu.find('.vue-treeselect__option').length
          if (updatedOptionCount > currentOptionCount) {
            // 有新选项加载,继续递归
            getAllOptions()
          } else {
            // 所有选项已加载,提取文本
            const allTexts = [...$updatedMenu.find('.vue-treeselect__option')].map(el => el.innerText.trim())
            groups.push(...allTexts)
            cy.log(groups)
          }
        })
    })
}

getAllOptions()

注意事项

  • 避免使用固定时间的wait(1000),改用.should('be.visible')可以更可靠地等待元素渲染完成。
  • 如果树形选项有特殊的层级类(比如子选项的.vue-treeselect__option--child),可以根据需求调整选择器,比如用.vue-treeselect__option:not(.vue-treeselect__option--disabled)排除禁用选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:37:32