Home Web Front-end JS Tutorial Detailed explanation of how Vue.js implements lists

Detailed explanation of how Vue.js implements lists

Dec 21, 2017 am 09:59 AM
javascript vue.js list

This article mainly shares with you the operation method of Vue.js to implement a list. Vue.js adopts the MVVM mode in design. When the View layer changes, it will automatically update to the ViewModel. Friends in need can refer to it, I hope it can help everyone.

1. Brief description of Vue.js

Vue.js (pronounced /vjuː/, similar to view) is a progressive framework for building user interfaces. Like the front-end framework Angular, Vue.js adopts the MVVM mode in design. When the View layer changes, it will automatically update to the ViewModel. Vice versa, the View and ViewModel are established through two-way data binding (data-binding). Contact, as shown in the figure below

Vue.js divides the view and data into two parts through the MVVM pattern (or decoupling the view code and business logic), so we only We need to care about data operations, DOM view updates and a series of other things, Vue will automatically handle it for us.

If two-way binding of data is implemented through the v-model instruction, the user enters any value in the input box, and the value of the message entered by the user is displayed in real time (corresponding to the above MVVM mode The relationship diagram is not difficult to understand)

<!DOCTYPE html>
<html>
<head>
  <title>Vue.js数据的双向绑定</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- 引入 Bootstrap -->
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://unpkg.com/vue"></script>
</head>
<body>
  <p class="container" id="app">
    <input v-model="message" placeholder="请任意输入" class="form-control">
    <p>Message is: {{ message }}</p>
  </p>
  <script type="text/javascript">
    new Vue({ //创建Vue实例
      el:"#app", //挂载创建Vue实例对象
      data: {
        message : "Hello Vue.js"
      },
      methods:{}
    })
  </script>
</body>
</html>
Copy after login

The following poster directly bypasses the basic syntax of Vue.js. If you don’t understand the basic syntax, you can consult relevant information. Starting from the case of elegant implementation of task list operations through Vue.js, we will The fragmented knowledge modules of Vue.js are integrated together.

Next, let’s experience the fresh/concise writing style of Vue.js (pronounced /vjuː/, similar to view).

2. Vue.js elegant implementation task list Operation

Vue.js To preview the elegant implementation of task list renderings, please click

## 3. HTML skeleton CSS style code

Use BootStrap The front-end responsive development framework, HTML skeleton and CSS style Demo are as follows

 <!DOCTYPE html>
 <html>
 <head>
   <title>Vue.js</title>
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <!-- 引入 Bootstrap -->
   <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
   <!-- 引入 vue.js -->
   <script src="https://unpkg.com/vue"></script>
   <style type="text/css">
     .list-group button { 
       background: none;
       border: 0;
       color: red;
       outline: 0;
       float: right;
       font-weight: bold;
       margin-left: 5px;
     }
   </style>
 </head>
 <body>
   <p class="container" id="app"> 
     <p v-show="remainTask.length>0">任务列表</p>
     <ul class="list-group">
        <li class="list-group-item">
          <span title="编辑任务">Vue.js - 是一套构建用户界面的渐进式框架</span>
          <button title="移除任务">✗</button>
          <button title="任务完成">✔</button>
        </li>
     </ul>
     <form>
       <p class="form-group">
        <label for="exampleInputEmail1">任务描述</label>
        <input type="text" class="form-control" placeholder="请输入你要添加的任务" required>
       </p>
       <p class="form-group"> 
         <button class="btn btn-primary" type="submit">添加任务</button>
       </p>
     </form>
     <p>已完成的Task</p>
     <ol class="list-group">
       <li class="list-group-item"> 
        JavaScript高级程序设计
       </li>
     </ol>
   </p>
 </body>
 </html>
Copy after login
4. Instantiate Vue and apply Vue instructions Directives to add projects

<p class="container" id="app" v-cloak>
     <p v-show="remainTask.length>0">任务列表 ({{remainTask.length}})</p>
     <ul class="list-group">
      <template v-for="task in remainTask">
        <li class="list-group-item">
          <span v-on:dblclick="editTask(task)" title="编辑任务">{{task.text}}</span>
          <button v-on:click="removeTask(task)" title="移除任务">✗</button>
          <button v-on:click="completeTask(task)" title="任务完成">✔</button>
        </li>
      </template>
     </ul>
     <form>
       <p class="form-group">
        <label for="exampleInputEmail1">任务描述</label>
        <input type="text" class="form-control" placeholder="请输入你要添加的任务" v-model="newTask" required>
       </p>
       <p class="form-group"> 
         <button class="btn btn-primary" type="submit" v-on:click="addTask">添加任务</button>
       </p>
     </form>
     <p>已完成的Task({{filterTask.length}})</p>
     <ol class="list-group">
       <template v-for="task in filterTask">
         <li class="list-group-item"> 
           {{task.text}}
         </li>
       </template>
     </ol>
   </p>
   <script type="text/javascript">
     var app = new Vue({  //创建Vue对象实例
       el:"#app", //挂载DOM元素的ID
       data: {
         tasks : [
           { text : "Vue.js - 是一套构建用户界面的渐进式框架", complete:false},
           { text : "Bootstrap 响应式布局", complete:false },
           { text : "Webpack前端资源模块化管理和打包工具", complete:false},
           { text : "Yarn 中文手册Yarn 是一个快速、可靠、安全的依赖管理工具", complete:true},
           { text : "JavaScript语言精粹", complete:false},
           { text : "JavaScript高级程序设计", complete:true}
         ],
         newTask:"程序员的修炼之道" //默认值
       },
       methods:{
         addTask:function(event){ //添加任务
           event.preventDefault();
           this.tasks.push({
             text: this.newTask,
             complete: false
           });
           this.newTask = "";
         },
         editTask:function(task){ //编辑任务
           //移除当前点击task
           this.removeTask(task);
 
           //更新vue实例中newTask值
           this.newTask = task.text;
         },
         removeTask: function(task){ //删除任务
           //指向Vue实例中的tasks
           _tasks = this.tasks;
           //remove
           _tasks.forEach(function(item, index){
             if(item.text == task.text){
               _tasks.splice(index, 1);
             }
           })
         },
         completeTask: function(task){ //任务完成状态
           task.complete = true; //设置任务完成的状态
         }
       },
       //用于计算属性,属性的计算是基于它的依赖缓存(如vue实例中的tasks) 
       //只有当tasks数据变化时,才会重新取值
       computed:{
         remainTask:function(){ //筛选未完成的记录
           return this.tasks.filter(function(task){ //filter过滤器
             return !task.complete;
           })
         },
         filterTask:function(){ //筛选已完成的记录
           return this.tasks.filter(function(task){
             return task.complete;
           })
         }
       }
     });
   </script>
Copy after login
v-cloak mainly solves the problem of slow page initialization and garbled characters Problems (such as displaying Vue value expressions on the display page);


v-show command simple switching of CSS properties, suitable for frequent switching of CSS properties from display)


The v-if command determines whether the page is inserted, which is relatively expensive to switch compared to v-show


v-on:dblclick, v-on:click page event binding


(such as v-on:dblclick(task) method name dblclick() parameter task is an object in the currently clicked tasks array


v-for iteration instruction loop traversal Array filter is mainly used to filter qualified data/date formatting, etc.


computed is used to calculate attributes. The calculation of attributes is based on its dependent cache (such as tasks in the vue instance). Only when tasks The value will only be reset when the data changes

PS: Let’s take a look at the effect of using Vue.js to achieve list selection

html

<p id="app">
 <p class="collection">
  <a href="#!" class="collection-item"
    v-for="gameName in gameNames"
    :class="{active: activeName == gameName}"
    @click="selected(gameName)">{{gameName}}</a>
 </p>
</p>
Copy after login
JS

new Vue({
 el: "#app",
 data: {
  gameNames: ['魔兽世界', '暗黑破坏神Ⅲ', '星际争霸Ⅱ', '炉石传说', '风暴英雄',
   '守望先锋'
  ],
  activeName: ''
 },
 methods: {
  selected: function(gameName) {
   this.activeName = gameName
  }
 }
})
Copy after login
After studying this article, have you mastered the method of implementing list in Vue.js? Let’s try it quickly.

Related recommendations:

Layout tags and list tags in html. Detailed graphic and text explanation

Usage summary of custom list item list-style

Introduction to how JavaScript implements automatic scrolling of Select list content

The above is the detailed content of Detailed explanation of how Vue.js implements lists. 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Unable to display win7 wireless network list Unable to display win7 wireless network list Dec 22, 2023 am 08:07 AM

In order to facilitate many people's mobile work, many notebooks are equipped with wireless network functions, but some people's computers cannot display the WiFi list. Now I will bring you how to deal with this problem under win7 system. Let's take a look. Bar. The wireless network list cannot be displayed in win7 1. Right-click the network icon in the lower right corner of your computer, select "Open Network and Sharing Center", open it and then click "Change Adapter Settings" on the left 2. After opening, right-click the mouse to select the wireless network adapter, and select "Diagnosis" 3. Wait for diagnosis. If the system diagnoses a problem, fix it. 4. After the repair is completed, you can see the WiFi list.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles