Vue learning on the third day

16052861:

Vue directive v-for

1. Function:

Render entire elements multiple times based on data loops → arrays , objects, numbers...

2. Traversing the array syntax:

v-for = "( item, index ) in array "
Ø Each item of item , index subscript
ØOmit index: v-for = " item in array "

key in v-for

Syntax: key attribute = "unique identifier", key function: unique identifier added to the element .
Function: The unique identifier added to the list item . It is convenient for Vue to correctly sort and reuse list items .
important point:
1. The value of the key can only be a string or a number
2. The value of key must be unique
3. It is recommended to use id as the key (unique), and it is not recommended to use index as the key (it will change and does not correspond)
<li v-for="(item, index) in xxx" :key="唯一值">

Vue directive v-model

1. Function: for form elements , two-way data binding → can quickly get or set the content of form elements
① Data change → view automatically updated
View changes → data is automatically updated
2. Syntax: v-model = 'variable'

Comprehensive Case: Little Black Notepad

Functional Requirements:
① List rendering
② Delete function
③ Add function
④ Bottom statistics and clearing
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./css/index.css" />
<title>记事本</title>
</head>
<body>

<!-- 主体区域 -->
<section id="app">
  <!-- 输入框 -->
  <header class="header">
    <h1>小黑记事本</h1>
    <input v-model="todoName"  placeholder="请输入任务" class="new-todo" />
    <button @click="add" class="add">添加任务</button>
  </header>
  <!-- 列表区域 -->
  <section class="main">
    <ul class="todo-list">
      <li class="todo" v-for="(item, index) in list" :key="item.id">
        <div class="view">
          <span class="index">{
       
       { index + 1 }}.</span> <label>{
       
       { item.name }}</label>
          <button @click="del(item.id)" class="destroy"></button>
        </div>
      </li>
    </ul>
  </section>
  <!-- 统计和清空 -->
  <footer class="footer" v-show="list.length > 0">
    <!-- 统计 -->
    <span class="todo-count">合 计:<strong> {
       
       { list.length }} </strong></span>
    <!-- 清空 -->
    <button @click="clear" class="clear-completed">
      清空任务
    </button>
  </footer>
</section>

<!-- 底部 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  // 添加功能
  // 1. 通过 v-model 绑定 输入框 → 实时获取表单元素的内容
  // 2. 点击按钮,进行新增,往数组最前面加 unshift
  const app = new Vue({
    el: '#app',
    data: {
      todoName: '',
      list: [
        { id: 1, name: '跑步一公里' },
        { id: 3, name: '游泳100米' },
      ]
    },
    methods: {
      del (id) {
        // console.log(id) => filter 保留所有不等于该 id 的项
        this.list = this.list.filter(item => item.id !== id)
      },
      add () {
        if (this.todoName.trim() === '') {
          alert('请输入任务名称')
          return
        }
        this.list.unshift({
          id: +new Date(),
          name: this.todoName
        })
        this.todoName = ''
      },
      clear () {
        this.list = []
      }
    }
  })

</script>
</body>
</html>
Function summary:
① List rendering:
v-for key setting { { }} interpolation expression
② Delete function
v-on calls the pass parameter filter to filter, overwrite and modify the original array
③ Add function
v-model binding unshift to modify the original array to add
④ Bottom statistics and clearing
Array.length cumulative length
overwrite array empty list
v-show control hidden

instruction modifier 

Use "." to specify some instruction suffixes , different suffixes encapsulate different processing operations simplify the code
① Button modifier
@keyup.enter
Keyboard carriage return monitoring
v-model modifier
v-model.trim remove leading and trailing spaces
v-model.number turn number
③ Event modifier
@event name.stop prevent bubbling
@ eventname.prevent prevent default behavior

Enhancements to v-bind for style control

In order to facilitate developers to control the style , Vue extends the syntax of v-bind , which can control the class name and style inline style .

Enhancement of v-bind for style control - operation class

Syntax : class = "object/array"
①Object → The key is the class name, and the value is a Boolean value. If the value is true , there is this class, otherwise there is no such class
<div class="box" :class="{ 类名1: 布尔值, 类名2: 布尔值 }"></div>
Applicable scenario: a class name, switching back and forth

②Array → All classes in the array will be added to the box, which is essentially a class list
<div class="box" :class="[ 类名1, 类名2, 类名3 ]"></div>
Applicable scenario: adding or deleting classes in batches
:class="['pink', 'big']"

Enhancement of v-bind for style control - operate style

Syntax : style = "style object"
<div class="box" :style="{ CSS属性名1: CSS属性值, CSS属性名2: CSS属性值 }"></div>
Applicable scenario: dynamic setting of a specific attribute

 v-model applied to other form elements

Common form elements can be associated with v-model binding → quickly get or set the value of form elements
v-model applied to other form elements it will automatically pick the correct method to update the element based on the control type
Input box input: text
textarea
check box input: checkbox
Single button input:radio
drop down menu select
...
→ value
→ checked
→ value
→ value
→ checked

 

computed property

Concept: New attributes calculated based on existing data . Dependent data changes and is automatically recalculated .
grammar:
① Declared in the computed configuration item , a computed property corresponds to a function
② It is used like a normal attribute using { { computed attribute name }}

 Computed property → can encapsulate a piece of evaluation code

 computed computed properties vs methods method

computed computed properties:
Function: Encapsulate a section of data processing and obtain a result .
grammar:
① Write in the computed configuration item
② As an attribute, directly use → this.Computed property { { calculated property }}
methods method:
Role: Provide a method for the instance to call to process business logic .
grammar:
① Write in the methods configuration item
② As a method, you need to call → this. method name ( ) { { method name () }} @event name =" method name "
Caching features (improving performance) :
Computed properties cache the calculated results , again using direct read caching,
Dependencies changed, automatically recalculated → and cached again

Computed property complete writing

  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./styles/index.css" />
    <title>Document</title>
  </head>
  <body>
    <div id="app" class="score-case">
      <div class="table">
        <table>
          <thead>
            <tr>
              <th>编号</th>
              <th>科目</th>
              <th>成绩</th>
              <th>操作</th>
            </tr>
          </thead>

          <tbody v-if="list.length > 0">
            <tr v-for="(item, index) in list" :key="item.id">
              <td>{
        
        { index + 1 }}</td>
              <td>{
        
        { item.subject }}</td>
              <!-- 需求:不及格的标红, < 60 分, 加上 red 类 -->
              <td :class="{ red: item.score < 60 }">{
        
        { item.score }}</td>
              <td><a @click.prevent="del(item.id)" href="http://www.baidu.com">删除</a></td>
            </tr>
          </tbody>

          <tbody v-else>
            <tr>
              <td colspan="5">
                <span class="none">暂无数据</span>
              </td>
            </tr>
          </tbody>

          <tfoot>
            <tr>
              <td colspan="5">
                <span>总分:{
        
        { totalScore }}</span>
                <span style="margin-left: 50px">平均分:{
        
        { averageScore }}</span>
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
      <div class="form">
        <div class="form-item">
          <div class="label">科目:</div>
          <div class="input">
            <input
              type="text"
              placeholder="请输入科目"
              v-model.trim="subject"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="label">分数:</div>
          <div class="input">
            <input
              type="text"
              placeholder="请输入分数"
              v-model.number="score"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="label"></div>
          <div class="input">
            <button @click="add" class="submit" >添加</button>
          </div>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

    <script>
      const app = new Vue({
        el: '#app',
        data: {
          list: [
            { id: 1, subject: '语文', score: 62 },
            { id: 7, subject: '数学', score: 89 },
            { id: 12, subject: '英语', score: 70 },
          ],
          subject: '',
          score: ''
        },
        computed: {
          totalScore() {
            return this.list.reduce((sum, item) => sum + item.score, 0)
          },
          averageScore () {
            if (this.list.length === 0) {
              return 0
            }
            return (this.totalScore / this.list.length).toFixed(2)
          }
        },
        methods: {
          del (id) {
            // console.log(id)
            this.list = this.list.filter(item => item.id !== id)
          },
          add () {
            if (!this.subject) {
              alert('请输入科目')
              return
            }
            if (typeof this.score !== 'number') {
              alert('请输入正确的成绩')
              return
            }
            this.list.unshift({
              id: +new Date(),
              subject: this.subject,
              score: this.score
            })

            this.subject = ''
            this.score = ''
          }
        }
      })
    </script>
  </body>
</html>

Summary of business technical points:

1. Rendering function (failing to highlight)
v-if v-else v-for v-bind:class
2. Delete function
Click the parameter pass filter to filter and overwrite the original array
.prevent prevents the default behavior
3. Add function
v-model v-model modifier (.trim .number)
Unshift modifies the array to update the view
4. Calculate the total score and calculate the average score
Calculate attribute reduce summation

 

 

Guess you like

Origin blog.csdn.net/cxxc980322/article/details/132009511