Home Web Front-end JS Tutorial Vue implements sample code to select all and none_vue.js

Vue implements sample code to select all and none_vue.js

Mar 31, 2018 pm 04:38 PM
javascript code Example

This article mainly introduces the sample code for implementing vue to select all and none. Now I share it with you and give you a reference. Let’s take a look together

The select all function can be said to be a very common function in front-end development. In the past, jQuery was mostly used in project development. Recently I was refactoring my previous project using the vue front-end framework. The transition from jQuery to Vue is mainly a change of thinking. It is to transform the original idea of ​​directly operating DOM into operating data. Using data to drive DOM is also a core idea of ​​the Vue framework. The change of thinking will lead to the realization of functions. Naturally easier to understand.

For example, in the simple demo below


If you do it according to the jQuery idea, you need to select the select all checkbox and All checkbox items register selected events respectively, determine the selected status to set the corresponding status for the relevant checkbox, which involves a lot of DOM operations.

Let’s take a look at the idea of ​​​​vue data-driven dom to achieve this function.

vue data-driven dom implementation function


<p class="checkbox">
  <label for="quan">
    <!-- 这里的 $event 是将当前对象传入进去,具体详情请参照vue官方文档 -->
    <input id="quan" type="checkbox" @click="checkAll($event)"> 全选
  </label>
  <label>
    <!-- v-model 双向数据绑定命令 -->
    <input class="checkItem" type="checkbox" value="apple" v-model="checkData"> apple
  </label>
  <label>
    <input class="checkItem" type="checkbox" value="banana" v-model="checkData"> banana
  </label>
  <label>
    <input class="checkItem" type="checkbox" value="orange" v-model="checkData"> orange
  </label>
</p>
<script>
  new Vue({
    el: &#39;#app&#39;,
    data(){
      return {
        checkData: [] // 双向绑定checkbox数据数组
      }
    },
    watch: { // 监视双向绑定的数据数组
      checkData: {
        handler(){ // 数据数组有变化将触发此函数
          if(this.checkData.length == 3){
            document.querySelector(&#39;#quan&#39;).checked = true;
          }else {
            document.querySelector(&#39;#quan&#39;).checked = false;
          }
        },
        deep: true // 深度监视
      }
    },
    methods: {
      checkAll(e){ // 点击全选事件函数
        var checkObj = document.querySelectorAll(&#39;.checkItem&#39;); // 获取所有checkbox项
        if(e.target.checked){ // 判定全选checkbox的勾选状态
          for(var i=0;i<checkObj.length;i++){
            if(!checkObj[i].checked){ // 将未勾选的checkbox选项push到绑定数组中
              this.checkData.push(checkObj[i].value);
            }
          }
        }else { // 如果是去掉全选则清空checkbox选项绑定数组
          this.checkData = [];
        }
      }
    }
  });
</script>
Copy after login


Using vue’s two-way data binding v-model command, when checked, the value of the checkbox will be automatically pushed to the bound array checkData, which saves a lot of operations on the DOM.

If it is a fixed option, this can be achieved, but this method has some disadvantages. Two-way binding of array data is hard-coded and not very flexible. If the checkbox option is added, the wach needs to be changed. Determine the length of the bound array.

Sometimes the checkbox option is dynamically obtained from the background, which makes it more flexible.

For example, the background data is like this:


  ajaxData: [{
    name: &#39;a&#39;,
    value: &#39;apple&#39;
  },{
    name: &#39;b&#39;,
    value: &#39;banana&#39;
  },{
    name: &#39;c&#39;,
    value: &#39;orange&#39;
  }]
Copy after login


You need to dynamically render the checkbox option first , performing data binding.


<p id="app">
  <p class="checkbox">
    <label for="quan">
      <!-- 这里的 $event 是将当前对象传入进去,具体详情请参照vue官方文档 -->
      <input id="quan" type="checkbox" @click="checkAll($event)"> 全选
    </label>
    <label v-for="item in ajaxData">
      <!-- v-model 双向数据绑定命令 -->
      <input class="checkItem" type="checkbox" :value="item.value" v-model="checkData"> {{item.name}}
    </label>
  </p>
</p>
<script>
  new Vue({
    el: &#39;#app&#39;,
    data(){
      return {
        ajaxData: [{ // 后台请求过来的数据
          name: &#39;选项1&#39;,
          value: &#39;apple&#39;
        },{
          name: &#39;选项2&#39;,
          value: &#39;banana&#39;
        },{
          name: &#39;选项3&#39;,
          value: &#39;orange&#39;
        }],
        checkData: [] // 双向数据绑定的数组
      }
    },
    watch: {
      checkData: { // 监视双向绑定的数组变化
        handler(){
          if(this.checkData.length == this.ajaxData.length){
            document.querySelector(&#39;#quan&#39;).checked = true;
          }else {
            document.querySelector(&#39;#quan&#39;).checked = false;
          }
        },
        deep: true
      }
    },
    methods: {
      checkAll(e){ // 点击全选事件
        if(e.target.checked){
          this.ajaxData.forEach((el,i)=>{
            // 数组里没有这一个value才push,防止重复push
            if(this.checkData.indexOf(el.value) == &#39;-1&#39;){ 
              this.checkData.push(el.value);
            }
          });
        }else { // 全不选选则清空绑定的数组
          this.checkData = [];
        }
      }
    }
  });
</script>
Copy after login



## method is not the optimal way to write , there are also some disadvantages. You are welcome to give us some advice and discuss them together.

github address: https://github.com/zhangqian00/

Related recommendations:

laravel5.3 vue implements the favorites function

Vue implements a cool menu plug-in detailed explanation



##

The above is the detailed content of Vue implements sample code to select all and none_vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What to do if the blue screen code 0x0000001 occurs What to do if the blue screen code 0x0000001 occurs Feb 23, 2024 am 08:09 AM

What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

The computer frequently blue screens and the code is different every time The computer frequently blue screens and the code is different every time Jan 06, 2024 pm 10:53 PM

The win10 system is a very excellent high-intelligence system. Its powerful intelligence can bring the best user experience to users. Under normal circumstances, users’ win10 system computers will not have any problems! However, it is inevitable that various faults will occur in excellent computers. Recently, friends have been reporting that their win10 systems have encountered frequent blue screens! Today, the editor will bring you solutions to different codes that cause frequent blue screens in Windows 10 computers. Let’s take a look. Solutions to frequent computer blue screens with different codes each time: causes of various fault codes and solution suggestions 1. Cause of 0×000000116 fault: It should be that the graphics card driver is incompatible. Solution: It is recommended to replace the original manufacturer's driver. 2,

Resolve code 0xc000007b error Resolve code 0xc000007b error Feb 18, 2024 pm 07:34 PM

Termination Code 0xc000007b While using your computer, you sometimes encounter various problems and error codes. Among them, the termination code is the most disturbing, especially the termination code 0xc000007b. This code indicates that an application cannot start properly, causing inconvenience to the user. First, let’s understand the meaning of termination code 0xc000007b. This code is a Windows operating system error code that usually occurs when a 32-bit application tries to run on a 64-bit operating system. It means it should

GE universal remote codes program on any device GE universal remote codes program on any device Mar 02, 2024 pm 01:58 PM

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

What does the blue screen code 0x000000d1 represent? What does the blue screen code 0x000000d1 represent? Feb 18, 2024 pm 01:35 PM

What does the 0x000000d1 blue screen code mean? In recent years, with the popularization of computers and the rapid development of the Internet, the stability and security issues of the operating system have become increasingly prominent. A common problem is blue screen errors, code 0x000000d1 is one of them. A blue screen error, or "Blue Screen of Death," is a condition that occurs when a computer experiences a severe system failure. When the system cannot recover from the error, the Windows operating system displays a blue screen with the error code on the screen. These error codes

Go language indentation specifications and examples Go language indentation specifications and examples Mar 22, 2024 pm 09:33 PM

Indentation specifications and examples of Go language Go language is a programming language developed by Google. It is known for its concise and clear syntax, in which indentation specifications play a crucial role in the readability and beauty of the code. effect. This article will introduce the indentation specifications of the Go language and explain in detail through specific code examples. Indentation specifications In the Go language, tabs are used for indentation instead of spaces. Each level of indentation is one tab, usually set to a width of 4 spaces. Such specifications unify the coding style and enable teams to work together to compile

A quick guide to learning Python drawing: code example for drawing ice cubes A quick guide to learning Python drawing: code example for drawing ice cubes Jan 13, 2024 pm 02:00 PM

Quickly get started with Python drawing: code example for drawing Bingdundun Python is an easy-to-learn and powerful programming language. By using Python's drawing library, we can easily realize various drawing needs. In this article, we will use Python's drawing library matplotlib to draw a simple graph of ice. Bingdundun is a cute panda who is very popular among children. First, we need to install the matplotlib library. You can do this by running in the terminal

Oracle DECODE function detailed explanation and usage examples Oracle DECODE function detailed explanation and usage examples Mar 08, 2024 pm 03:51 PM

The DECODE function in Oracle is a conditional expression that is often used to return different results based on different conditions in query statements. This article will introduce the syntax, usage and sample code of the DECODE function in detail. 1. DECODE function syntax DECODE(expr,search1,result1[,search2,result2,...,default]) expr: the expression or field to be compared. search1,

See all articles