<p>&quot;<template>\n  <div class="chooser-component">\n    <ul class="chooser-list">\n      &lt;li\n        v-for=&quot;(item, index) in selections&quot;\n        :key=&quot;index&quot;\n        @click=&quot;toggleSelection(index)&quot;\n        :title=&quot;item.label&quot;\n        :class=&quot;{active: checkActive(index)}&quot;\n      &gt;{{ item.label }}\n      </li>\n    </ul>\n  </div>\n</template>\n\n<script>\n  import _ from 'lodash'\n\n  export default {\n    props: {\n      selections: {\n        type: Array,\n        default: [{\n          label: 'test',\n          value: 0\n        }]\n      }\n    },\n    data () {\n      return {\n        nowIndexes: [0]\n      }\n    },\n    methods: {\n      toggleSelection (index) {\n        if (this.nowIndexes.indexOf(index) === -1) {\n          this.nowIndexes.push(index)\n        } else {\n          this.nowIndexes = _.remove(this.nowIndexes, (idx) =&gt; {\n            return idx !== index\n          })\n        } \n        let nowObjArray = _.map(this.nowIndexes, (idx) =&gt; {\n          return this.selections[idx]\n        })\n        this.$emit('on-change', nowObjArray)\n      },\n      checkActive (index) {\n        return this.nowIndexes.indexOf(index) !== -1\n      }\n    }\n  }\n</script>\n\n<style scoped>\n  .chooser-component {\n    position: relative;\n    display: inline-block;\n  }\n\n  .chooser-list li {\n    display: inline-block;\n    border: 1px solid #e3e3e3;\n    height: 25px;\n    line-height: 25px;\n    padding: 0 8px;\n    margin-right: 5px;\n    border-radius: 3px;\n    text-align: center;\n    cursor: pointer;\n  }\n\n  .chooser-list li.active {\n    border-color: linear-gradient(248deg, #ff8c1f, #ff6a00);\n    background: linear-gradient(248deg, #ff8c1f, #ff6a00);\n    color: #fff;\n  }\n</style>\n\n该前端代码是一个选择器组件,用于在用户进行选择时切换选项的状态。该组件接受一个名为selections的属性,该属性是一个数组,包含了选择器的选项。每个选项都有一个label和一个value。默认情况下,选择器只有一个选项,标签为&quot;test&quot;,值为0。\n\n组件中的nowIndexes是一个数组,用于存储当前选中的选项的索引。toggleSelection方法用于切换选项的状态,当点击一个选项时,如果该选项的索引不在nowIndexes中,则将其添加到nowIndexes中,否则将其从nowIndexes中移除。然后,根据nowIndexes中的索引获取当前选中的选项,并通过$emit方法触发on-change事件,将当前选中的选项传递给父组件。\n\ncheckActive方法用于判断一个选项是否处于选中状态,如果该选项的索引在nowIndexes中,则返回true,表示该选项处于选中状态。\n\n在样式中,chooser-component是一个相对定位的内联块元素,chooser-list li是选择器的选项样式,具有边框、高度、行高、内边距、边框半径等属性。选中的选项则具有不同的边框颜色、背景色和文字颜色。\n\n总之,这个前端代码实现了一个简单的选择器组件,可以根据用户的选择切换选项的状态,并通过事件向父组件传递当前选中的选项。</p>

原文地址: https://www.cveoy.top/t/topic/pyZg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录