【问题标题】:Vuejs How the select range of buttonVuejs如何选择按钮的范围
【发布时间】:2021-08-13 06:48:49
【问题描述】:

我有一个问题,

我在 v-for 中有一些按钮,例如,我需要允许用户从 A 到 C 进行选择,如图所示。此外,用户可以按下按钮,例如 D。 我的 v-for 看起来像这样

<menu-item 
   v-for="(item, index) in menu"
   :key="`item_${index}`"
   @click="setMenuItem(index, item.name)"
/>

然后我有数据属性selectedItems,当用户点击setMenuItem() 时,我在其中添加所有项目。

当用户单击一个项目时的选项工作正常,但当用户从 A 到 C 选择时,我无法使其工作。

通常,我需要的是,例如,当单击从 A 到 C 的一系列按钮时,我想将每个 item.name 推入我的 selectedItems 数据属性,我将第二个参数传递给我的 setMenuItem()

图形 graphic

【问题讨论】:

    标签: javascript vue.js range vuejs3


    【解决方案1】:

    要做到这一点,您首先必须有办法检查index 是否属于range

    你可以像这样创建一个常量:

    const RangeSelection = [0,1,2] // 你也可以添加名字。我正在索引。

    现在你 setMenuItem 功能只需添加此检查。

    setMenuItem(index,name) {
        if(RangeSelection.includes(index)) {
            // this is range selection
             
    
        } else {
             // this is single selection
             this.selectedItems = [];
             this.selectedItems.push(name)
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      setMenuItem方法中,你有参数index可以用来设置选择的值,例如:

      options = [{name: 'a'},{name: 'b'},{name: 'c'}]
      selectedValue = [];
      setMenuItem(index, name) {
        this.selectedValue = [...options].slice(0, index)
      }
      

      对于我单击菜单b 的示例,selectedValue 将包含[{name: 'a'},{name: 'b'}]

      上面代码的问题是它会从索引 0 开始,因此你需要再添加一个验证来计算它是否是开始索引,你可以使用这个逻辑(注意,你必须传递整个项目 @ 987654327@在组件中)

      setMenuItem(index, item) {
        const start = this.selectedValue.findIndex((selected) => item.name === selected.name)
        this.selectedValue = [...options].slice(start || 0, index + 1)
      }
      

      【讨论】:

        猜你喜欢
        • 2023-02-04
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 2020-11-17
        相关资源
        最近更新 更多