Работа с чекбоксами в Vue
Давайте теперь посмотрим, как происходит работа с чекбоксами. Пусть у нас есть следующий чекбокс:
Сделаем свойство checked , которое будет управлять работой этого чекбокса:
Привяжем это свойство через v-model :
Если чекбокс отмечен — свойство checked будет иметь значение true , а если не отмечен — то false . Чтобы убедится в этом, можно вывести значение свойства на экран, вот так:
С помощью тернарного оператора можно выводить что-нибудь более осмысленное:
Дан чекбокс. Дан абзац. С помощью директивы v-if сделайте следующее: если чекбокс отмечен — абзац должен быть показан, а если не отмечен — то скрыт.
Building a checkbox component in Vue
Prabhu Murthy
In this tutorial, we'll look at how to create checkbox and checkbox group components in Vue.js.
In Vue, UI components can be developed using the Options API or the newer Composition API.
The Options API uses options such as data, methods, and computed to define the UI component. The Composition API, on the other hand, comes with a set of APIs that allow us to build components using imported functions instead of declaring options. In this tutorial, we'll be using the Composition API.
We'll also use the SFC (Single File Components) approach for component development.
An SFC file has three parts: the script, the template, and the style. The script section is where all the JavaScript code goes. The HTML code will be put in the template section. In the style section, the styles for the HTML will be written.
Here is the typical structure of an SFC file:
As you can see, all of the UI code is contained in one place. This eliminates the need to switch between files frequently while developing UI components.
Checkbox
Let’s get started by creating a checkbox.vue file and defining some props under the script section.
We've set up five properties:
- value — value of the checkbox
- label — label for the checkbox
- checked-boolean checked state of the checkbox
- id-unique id of the checkbox. We’ll generate unique IDs with the nanoid library.
- disabled-boolean disabled state of the checkbox
defineProps returns a props object, which can be used to access all of the props in the SFC file's script and template sections.
Next, we define emits using defineEmits. Emits are used to define custom events in Vue. A parent or host will usually listen to the event and take in the data that the child provides. In our case, the checkbox group is the parent component that will listen to this event.
The next step is to create two computed properties. Most of the time, computed properties are used to calculate values when any reactive dependencies change.In our case, the computed properties will monitor the checked props and generate class names accordingly.
The first computed property (wrapperClass) is applied to the checkbox wrapper element.
When the checked state is true, the string "check-box–checked" is included in the wrapperClass property.
Before we set up the next computed property, let's quickly see how to use SVG icons, as we'll need two different icons to represent the checked and unchecked states. If you're developing with vite, you can use the vite-svg-loader library to use SVG files directly in your project.
Here are some examples of how to use vite-svg-loader to load SVG files in vue.
After setting up the icon configuration, let's write a computed property that uses the checked prop to show the checked or unchecked icon.
Now that we have the computed properties ready, it's time to set up an event handler for the click event.
When the checkbox is clicked, the handler emits the onChange event that we denied earlier via the definEmits and passes the checkbox's id.
In a short while, we will see how to capture this event in the parent component and execute some action based on the id passed. But first, some HTML.
Now that we've set up the properties and event handlers, let's go ahead and create some basic HTML.
In an SFC file, all HTML code should be wrapped in a template tag. Let's take a closer look at how the parent div will look.
We've defined a number of attributes for the div, so let's look at what each one means.
class: Class names are attached to HTML elements using the class attribute (note, unlike className in React). The ":" in front of the class indicates that the value of the class will be bound to a property defined in the script section. In our case, the class is bound to the computed property wrapperClass that we created earlier.
tabindex: tabindex is an HTML property that allows you to focus on an HTML element using the keyboard.
role: The role attribute is used to describe the type of HTML element. This is mostly used by screen readers, and in our case, we set the value to checkbox.
aria-checked: The ARIA attribute aria-checked describes the current state of the checkbox. (ARIA attributes are HTML attributes that make the user interface more accessible, particularly for screen reader users.) The value has been bound to the checked prop in this case. Every time the state of the checkbox changes, the value of this attribute changes to true or false.
Let's take a look at the div's contents. Within the div, we will show two elements.
- An Icon to signify the state of the checkbox
- A Label for the checkbox
Let’s run through them.
Here, the span element's class property is bound to the iconClass computed property we defined earlier.
As previously stated, we'll use two SVG icons to represent the checked and unchecked states.
- Square Icon: Unchecked state
- Checked Square: Checked state
The tutorial makes use of SVG icons from the Feathers icon set. You can choose icons from the same library or from your favorite icon set.
v-if is a Vue.js directive that conditionally renders an HTML element based on a value or prop. When the checked prop is true, we display the CheckedSquare icon, and when it is false, we show the Square icon.
Label
We use a span to display the label. The id for the span is generated on the fly using the id prop. This ID is important since it will be how the parent group component knows which boxes are checked.
This is how the entire template should look.
Styles
Finally, let's add some style to the checkbox to make it look nicer.
Styles are scoped locally, and you don’t have to worry about class names colliding.
We can quickly test the checkbox component that we created with the following code.
If all goes well, you should have the checkbox rendered as below.
Checkbox group
Beyond using a single checkbox in your form, you may want to present your users with a list of options and allow them to select a subset of those options. It's called a checkbox group in UI/UX terms, and that's what we'll build next.
Let's start by defining the properties, emits, and refs for the checkbox group.
Properties
We will define a single prop called “items” of type Array. The items prop represents a collection of checkboxes. Each item contains the id, name, value, and checked state of the checkbox.
Emits
Next, we need to use defineEmits to set up the onChange event. This will be used to send out a change event whenever one of the checkboxes changes its state.
Refs are reactive data sources. Whenever the ref data is updated, the view bound to the ref is automatically re-rendered to reflect the new data state.
The checkbox collection passed via the items prop is transformed and stored in itemsRef.
While storing the array in its initial state, we also include a unique id for every item with the help of nanoid.
Event handler
The checkbox group should process the change events originating from each checkbox and update the state accordingly. For this purpose, we need an event handler.
The event handler takes an id as a parameter and toggles the checkbox's state.
The next line from the above snippet takes the data from the checkboxes and turns it into a new array with the checked state turned on for the item with the matching id.
The reactive data source is then updated with the following snippet.
Finally, we emit the onChange event with the updated array.
Next, we need to create the HTML for the checkbox group.
In the above code, the outer div serves as a wrapper for all the checkboxes.
The v-for directive is a Vue.js directive that is used to render collections. In our case, we're rendering a list of checkboxes. Along with that, we also need to pass down the properties of each checkbox item.
The following lines pass the properties down to the checkbox component.
The properties of the checkbox component are id, label, value, and checked. The additional key property is important for rendering lists efficiently, and the value for it should be unique. For this reason, “id” is passed as the value for :key.
The main purpose of the key property is to help Vue's virtual DOM algorithm find vnodes when comparing the new list of nodes to the old list. Vue uses these keys to figure out which HTML elements it needs to remove, update, or add to the list.
Finally, we wire up the handleOnChange with the following code.
Whenever a change event is emitted by any of the checkbox components, the handleOnChange method gets invoked and sets the state of the checkboxes appropriately.
Now that we have both the checkbox and checkbox-group ready, let's see how the finished code for both the checkbox and checkbox-group looks.
checkbox.vue
checkbox-group.vue
Checkbox group in action
Now that we've created the checkbox group, let's put it to use.
In this code, we have imported the checkbox group within the script tag and used it under the template section like any other HTML tag. An array of options is passed to the component via the items prop.
If all goes well, then you should see the checkbox group rendered as below.
For reference and learning, the entire Vue project is available on codesandbox.
To sum it up.
In this tutorial, we used Vue's new composition API to build a checkbox and a checkbox group. Along the way, we learned how to use the brand-new API to expose props and emit events, as well as how to structure vue components using the SFC concept.
Building a file picker component in React
In this post, we build an advanced file picker in React, complete with drag and drop support. Code sandbox included!
Introducing the Explorer—manage your app’s components and code from one place
We’ve redesigned the left panel of the app editor to help you navigate to anything in your app from one place. The new left panel now includes tabs for Explorer and State. Explorer
Русские Блоги
Простейшая реализация: в раскрывающемся списке Vue выберите все и отмените флажок Vue, чтобы увеличить функцию выбора всех.
Введение: Раскрывающийся список радио в Vue очень прост в разработке, просто выберите вариант с v-for

Что мы должны делать, когда мы хотим сделать выпадающий список с несколькими вариантами выбора? Какой самый простой способ? Например, следующая картина:

Если вы выполняете поиск в Интернете, поиск — это группа детей, идея обхода дерева отличается от раскрывающегося списка с множественным выбором, и ее сложно написать.
Без дальнейших церемоний, сначала перейдите к исходному коду,GitHub-bill-mark / Vue-list-allchecked_suppurt: раскрывающийся список vue поддерживает полный выборНе понимаю исходный код и читайте дальше:
Требования: Бэкэнд передает объект массива на внешний интерфейс, каждый объект имеет идентификатор и имя, а внешний интерфейс передает идентификатор выбранного объекта на внутренний интерфейс.
Анализ: внешний интерфейс сначала объявляет пустой массив, после получения объекта массива, возвращенного серверной частью, добавьте имя для всех объектов, ниже приведен пример исходного кода

Далее напишите HTML:

JS только смотрит этот массив без написания дополнительных методов, он достаточно прост.
Есть два основных момента:
1.Vue хочет наблюдать за изменениями объекта массива, его нужно объявить как deep, что означает глубокое наблюдение.
Причина: Vue будет перемещать данные в дерево, только наблюдать за самим указанным узлом, если у узла есть дочерние узлы, он не будет управляться, и добавление глубины означает, что Vue также может наблюдать за дочерними узлами.
2. Объект с именем «all» имеет на один атрибут last_state больше, чем другие объекты.
Поскольку JS назначает массив переменной, на самом деле ссылка на эту переменную указывает на этот массив. В просмотре Vue ссылка на старое значение и новое значение указывает на один и тот же массив. Когда пользователь нажимает select all, он не может судить, прежде чем выбрать all. Независимо от того, выбрано ли это состояние или нет, последнее состояние должно быть сохранено в last_state. Когда пользователь нажимает select all, если last_state имеет значение true, это означает, что операция выбора всех отменяется, если last_state имеет значение false, это означает, что проверка выбрана. операционная
Есть одна непрофильная точка:
Как выбрать все поля после выполнения подвыбора? Или после всех выборов удалить дочерний узел и как удалить родительский (псевдо) узел?
Решение: объявите пустой массив в элементе watch, затем добавьте элементы с состоянием true, остальное — больше суждения,
Наконец, возьмите идентификатор пустого массива, объявленного часами, и передайте его бэкэнду.
Takeaway:
Get your feet wet with some of the new Vue 3 features while building a fully functional checkbox component. We’ll be using Font Awesome to replace the default html checkbox and Tailwind CSS to handle styling.
Code Sandbox:
To make it easy to code-along, I’ve put together a couple code sandboxes.
-
Fork this one to code along tl;dr
Lets get started
In the Starting Point sandbox we’ve got a basic checkbox input set up in ./components/checkbox.vue
We’re importing the checkbox.vue component into App.vue like so:
It seems to be working great. Only thing is, this checkbox is not tied to any data
We’ll take the following steps to get this checkbox working:
- Add data to App.vue and use v-model to tie the data to <check-box>
- In checkbox.vue sync the <input> checked prop to the value passed in by v-model
- Replace the default checkbox with Font Awesome icons
Step 1
To add the data to App.vue we could use the Options API, which would be what you’re used to if you’ve been using Vue for a while now.
But for the sake of learning something new, let’s use Vue3’s Composition API.
Everything bold in the code snippet below is what we’ll add to App.vue
setup() is the entry point for the composition API.
We declare our variable volumeOn and make it reactive by using ref() Notice that we need to import ref in order to use it. More on refs and reactivity here, it is vital read up on this aspect of Vue3.
We return volumeOn in order for the template to access the variable.
Let’s use v-model to bind the variable to the checkbox component.
With Vue3 we can now pass arguments to v-model ! We are passing checked as an argument. If we omitted this argument, volumeOn ’s value would be passed to the child component as value — but in our case checked will be passed. Its worth noting that v-model arguments allow for multiple v-models to be used on a component. More on that here.
Step 2
We need to update our checkbox.vue component to utilize the data we are passing in. First we’ll add a prop called checked with the expected value type to be a Boolean This will catch the value passed by v-model:checked
Now let’s tie the input’s checked property to our checked prop.
fyi :checked is shorthand for v-bind:checked
Test it out by changing const volumeOn = ref(true); to false and reloading. The checkbox should now be unchecked by default.
It looks like everything might be working alright, but let’s see if the value of volumenOn is changing at all when we click the box.
The quickest way in codesandbox would be by adding << volumeOn >> to the template somewhere.
Spoiler alert, the value does not change We need to emit the checked value from the checkbox component to sync the value
update:checked is a custom event synced to v-model:checked event.target.checked is the value we’re passing.
Now everything should be working with our checkbox.
If << volumeOn >> is not showing the proper value at this point, reload CodeSandbox, it should work fine.
Step 3
Finally, let’s get rid of those default checkbox styles, and replace them with Font Awesome icons.
We’ll add an icon in the label tag in checkbox.vue and hide the input with a Tailwind CSS class.
Here’s how the icon break down:
- fa provides all the default font awesome styles
- fa-check-square will give us a nice little check in a square, there are thousands of icons to pick from, check them out here
- text-blue-600 is a Tailwind CSS class, see all the options they have here
- mr-2 will give us a little right margin
But wait; we don’t want a blue checkbox when the checkbox is unchecked. Let’s add some logic to this class list for an unchecked box using Vue.
We’ve added :class for any dynamic classes which will allow us to utilize our component’s props or other data to determine which classes to use. Learn more here.
And there you have it, a fully functional checkbox component.
Update
Want to bind multiple custom checkboxes to the same array?
We can achieve this with just a few adjustments to our code for the single checkbox. Check it out here