


How to operate custom instructions in Vue to implement checkbox selection function
Below I will share with you a method for implementing Vue custom instructions to implement the checkbox selection function. It has a good reference value and I hope it will be helpful to everyone.
A project I recently worked on needed to use Vue to implement the select-all function. I looked at the online practices and found that the reusability of using attribute calculations was not high, so I chose custom instructions. However, most of the online practices are There will be certain format requirements for the original data, and no results will be returned, so improvements were made.
The above code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p id="app"> <input type="checkbox" v-model="allCheck" v-check-all="allCheck" check-data="list" result="customerResult" key="demo"> 全选 <ul> <li v-for="item in list"> <input type="checkbox" v-model="item.checked"> {{item.demo}} </li> </ul> <p > customerResult: {{customerResult}} </p> </p> <script src="vue.js"></script> <script> var vm = new Vue({ el: "#app", data:function(){ return { list:[{demo:1}, {demo:2}, {demo:3}], allCheck:'', customerResult:'', } }, directives: { 'check-all': { twoWay: true, params: ['checkData','result','key'], bind() { /*为原始数据的每一个对象添加一个checked属性*/ this.vm[this.params.checkData].forEach((item)=>{ Vue.set(item,'checked',false) }); /*提取被选中的项*/ this.setValue=function(){ let result=[] this.vm[this.params.checkData].forEach((item) => { if(item.checked){ result.push(item[this.params.key]) } }); this.vm[this.params.result]=result } /*如果所有的列表的checked属性都为true,则选中全选框,否则不选中全选框 */ this.vm.$watch(this.params.checkData, (data) => { if(data.every((item) => item.checked)) { this.set(true); } else { this.set(false); } this.setValue() }, {deep: true}); }, // checkAll发生更改时 update(checkAll) { /*如果全选框被选中,则将列表的所有checked属性转为true,否则转为false */ if(checkAll) { this.vm[this.params.checkData].forEach((item) => { item.checked = true; }); } else { this.vm[this.params.checkData].forEach((item) => { item.checked = false; }); } this.setValue() }, }, } }) </script> </body> </html>
Usually we have to get a certain key value in the original data, which can be found in Fill in "key" with the key value you want to obtain, and "result" is the selected item.
Sometimes, we need to return a complete object and modify the code. When the key is not entered, a complete object array is returned.
this.setValue=()=>{ let result=[] this.vm[this.params.checkData].forEach((item) => { //删除checked属性 let temp={}; (()=>delete Object.assign(temp,item).checked)(); item.checked?result.push(item[this.params.key]||temp):""; }); this.vm[this.params.result]=result }
But when, At this time, the object in the returned array does not have the same reference address as the original data. When the array.$remove() function needs to be used, it will fail. A new relative parameter is added, and the user can customize the returned data. Whether it is associated with the original data
this.setValue = () => { let result = [] this.vm[this.params.checkData].forEach((item) => { if(this.params.relative) { item.checked ? result.push(item) : ""; }else{ //删除checked属性 let temp = {}; (() => delete Object.assign(temp, item).checked)(); item.checked ? result.push(item[this.params.key] || temp) : ""; } }); this.vm[this.params.result] = result }
When the data length is greater than 2, it needs to be judged 2N times, which consumes a lot of performance. Optimize it:
'check-all', { twoWay: true, params: ['checkData', 'result', 'key','relative'], /*checkData:列表数据, result:返回的结果, key:列表数据中需要返回的字段, relative:是否返回与列表数据相同引用地址的选中结果*/ bind() { /*提取被选中的项*/ this.setValue = () => { let result = [] if (this.params.relative) { this.vm[this.params.checkData].forEach((item) => { item.checked ? result.push(item) : ""; }); } else { this.vm[this.params.checkData].forEach((item) => { //删除checked属性 let temp = {}; (() => delete Object.assign(temp, item).checked)(); item.checked ? result.push(item[this.params.key] || temp) : ""; }); } this.vm[this.params.result] = result }; /*为原始数据的每一个对象添加一个checked属性*/ this.addChecked = () => { this.vm[this.params.checkData].forEach((item) => { Vue.set(item, 'checked', false) }); }; /*如果所有的列表的checked属性都为true,则选中全选框,否则不选中全选框 */ this.vm.$watch(this.params.checkData, (data) => { if(!data.length) return; data.every((item) => item.checked) ? this.set(true) : this.set(false); this.setValue() }, {deep: true}); //当列表发生变化时重新绑定 this.vm.$watch(this.params.checkData, (data) => { if(!data.length) return this.addChecked(); }); }, // checkAll发生更改时 update(checkAll) { /*如果全选框被选中,则将列表的所有checked属性转为true,否则转为false */ checkAll ? this.vm[this.params.checkData].forEach((item) => { item.checked = true }) : this.vm[this.params.checkData].forEach((item) => { item.checked = false }); this.setValue() }, }
At this time, you only need to judge N 1 times.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
p5.js introductory tutorial - Example of mouse interaction
Four ways to implement two-way binding with Vue A method
Vue-Routing navigation menu bar highlight setting method
The above is the detailed content of How to operate custom instructions in Vue to implement checkbox selection function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to get items using commands in Terraria? 1. What is the command to give items in Terraria? In the Terraria game, giving command to items is a very practical function. Through this command, players can directly obtain the items they need without having to fight monsters or teleport to a certain location. This can greatly save time, improve the efficiency of the game, and allow players to focus more on exploring and building the world. Overall, this feature makes the gaming experience smoother and more enjoyable. 2. How to use Terraria to give item commands 1. Open the game and enter the game interface. 2. Press the "Enter" key on the keyboard to open the chat window. 3. Enter the command format in the chat window: "/give[player name][item ID][item quantity]".

An avatar on Netflix is a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.
