Home  >  Article  >  Web Front-end  >  How to implement segmented selection component using Vue?

How to implement segmented selection component using Vue?

WBOY
WBOYOriginal
2023-06-25 11:53:42989browse

Vue is one of the most popular front-end development frameworks today, with many efficient and easy-to-use features, such as data binding, componentization, responsiveness, etc. Segment selection is a common UI component that allows users to select one or more segments. It is usually used in scenarios such as query conditions, label filtering, and data filtering. This article will introduce how to use Vue to implement a segmented selection component.

  1. Preparation work

Before we start, we need to prepare the following files:

  1. index.html: Contains the introduction of Vue and components Hang in the code
  2. Segment.vue: The code of the segment selection component

Add the following code in the index.html file:

<!DOCTYPE html>
<html>
  <head>
    <title>Segment Selector Component</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@3.0.0/dist/vue.global.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script src="app.js"></script>
  </body>
</html>

Here we use Vue A global build of 3.0 and introduced into the page. A script named app.js is also introduced for mounting components.

Next create the app.js file and add the following code:

import Segment from './Segment.vue';

const app = Vue.createApp({});
app.component('Segment', Segment);
app.mount('#app');

Here we use the API of Vue 3.0 to create an empty application instance and register a component named Segment. , and mount it on the DOM element with the id app. At the same time, we also need to create a file named Segment.vue to implement the code of the segment selection component.

  1. Implementing the segment selection component

In the Segment.vue file, we implement a component named Segment. We need to add three props: data, selectedIndex and multiSelect. data is the segmented data source, selectedIndeX is the currently selected segmented index, and multiSelect indicates whether to enable multi-select mode. At the same time, we need to define a method handleSegmentClick in the component to handle segmented click events.

<template>
  <div class="segment-container">
    <div
      v-for="(segment, index) in data"
      :key="index"
      :class="{
        'segment': true,
        'segment-active': multiSelect ?
          selectedIndex.includes(index) :
          selectedIndex === index
      }"
      @click="handleSegmentClick(index)"
    >
      {{ segment }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'Segment',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    selectedIndex: {
      type: [Number, Array],
      default: -1
    },
    multiSelect: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    handleSegmentClick(index) {
      let selected = this.selectedIndex;

      if (this.multiSelect) {
        selected = (Array.isArray(selected)) ? selected : [];
        if (selected.includes(index)) {
          selected.splice(selected.indexOf(index), 1);
        } else {
          selected.push(index);
        }
      } else {
        selected = index === selected ? -1 : index;
      }

      this.$emit('update:selectedIndex', selected);
    }
  }
};
</script>

In the template part, we use v-for to traverse each segment in the data source and add active styles to the selected segments through style binding instructions. At the same time, by binding events with @click, we implement segmented click event processing.

In the script section, we define a method named handleSegmentClick to handle segmented click events. In the method, we first obtain the currently selected segment and perform different processing according to the status of multi-selection mode or not. Specifically, in multi-select mode, we store the selected state in the array selected, and when a segment is selected, we add the index of the current segment to selected, otherwise we remove the index of the segment from selected. In radio selection mode, we only store the selected segment index in selected. If the clicked segment is already selected, the selected state is cleared.

Finally, we pass the updated selected state back to the parent component through this.$emit. And bind the handleSegmentClick method to the @click event in the template.

  1. Using segment selection component

In the index.html file, we create a variable named segmentData, which is an array type, and use it as a component props passed to the Segment component.

<div id="app">
  <Segment
    :data="segmentData"
    :selected-index.sync="selectedIndex"
    :multi-select="multiSelect"
  />
</div>

As you can see, we configured three props: data, selectedIndex and multiSelect. selectedIndex uses the .sync modifier to support two-way data binding.

Next, we add the following code in app.js for data initialization and related processing:

import Segment from './Segment.vue';

const app = Vue.createApp({
  data() {
    return {
      segmentData: ['Web Development', 'Data Science', 'Mobile Development'],
      selectedIndex: 0,
      multiSelect: false
    };
  },
  methods: {
    toggleSelection() {
      this.multiSelect = !this.multiSelect;
      this.selectedIndex = this.multiSelect ? [0, 2] : 0;
    }
  }
});

app.component('Segment', Segment);

app.mount('#app');

In the data method, we initialize three variables: segmentData, selectedIndex and multiSelect. segmentData is the segment data source we need to select, selectedIndex is used to record the currently selected segment index, and multiSelect indicates whether segment selection enables multi-selection mode.

In methods, we define a method called toggleSelection, in which we toggle the value of multiSelect and set the value of selectedIndex according to its state. Specifically, when multiSelect is true, we set selectedIndex to [0, 2], indicating that the first and third segments are selected, otherwise we set selectedIndex to 0, indicating that the first segment is selected .

  1. Summary

In this article, we introduced how to use Vue to implement a segmented selection component. This component is a general UI component that can be used in a variety of scenarios, such as query conditions, label filtering, data filtering, etc. Through the introduction of this article, readers can learn how to use Vue to implement important features such as data binding, componentization, and responsiveness, and deepen their understanding and use of Vue.

The above is the detailed content of How to implement segmented selection component using Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn