Getting started with front-end Vue-day02

(Creating is not easy, thank you, your support is the biggest motivation for me to move forward, if it is helpful to you after reading it, please leave your footprints)

Table of contents

Instruction Supplement

instruction modifier

Enhancements to v-bind for style control 

operation class

Case: Jingdong spike tab navigation highlight

operation style 

v-model applied to other form elements 

computed computed properties

basic grammar

computed computed properties vs methods method

Computed property complete writing

Comprehensive Case- Achievement Case

watch listener

basic grammar

complete writing 


Instruction Supplement

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 the style control of developers , Vue extends the syntax of v-bind , which can control the class name and style inline style

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
        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 

 

         Applicable scenario: adding or deleting classes in batches 

Case: Jingdong spike tab navigation highlight

Core ideas:
1. Dynamically render tab based on data → v-for
2. Prepare the subscript to record which tab is highlighted activeIndex
3. Based on the subscript, dynamically control the class name
v-bind:class
The so-called switching highlight is actually changing the subscript
<!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">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    ul {
      display: flex;
      border-bottom: 2px solid #e01222;
      padding: 0 10px;
    }
    li {
      width: 100px;
      height: 50px;
      line-height: 50px;
      list-style: none;
      text-align: center;
    }
    li a {
      display: block;
      text-decoration: none;
      font-weight: bold;
      color: #333333;
    }
    li a.active {
      background-color: #e01222;
      color: #fff;
    }

  </style>
</head>
<body>

  <div id="app">
    <ul>
      <li v-for="(item,index) in list" :key="item.id" @click="activeIndex = index">
        <a :class="{active:activeIndex===index}" href="#">{
   
   {item.name}}</a>
      </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        activeIndex:0,//记录高亮
        list: [
          { id: 1, name: '京东秒杀' },
          { id: 2, name: '每日特价' },
          { id: 3, name: '品类秒杀' }
        ]

      }
    })
  </script>
</body>
</html>

The web page appears as: 

operation style 

Syntax : style = "style object"

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
It will automatically pick the correct method to update the element based on the control type
Input box input:text                                  → value
textarea textarea → checked
check box input: checkbox → value
Single button input: radio → value
drop-down menu select → checked
...
<!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">
  <title>Document</title>
  <style>
    textarea {
      display: block;
      width: 240px;
      height: 100px;
      margin: 10px 0;
    }
  </style>
</head>
<body>

  <div id="app">
    <h3>小周学习网</h3>

    姓名:
      <input type="text" v-model="username"> 
      <br><br>

    是否单身:
      <input type="checkbox" v-model="isSingle"> 
      <br><br>

    <!-- 
      前置理解:
        1. name:  给单选框加上 name 属性 可以分组 → 同一组互相会互斥
        2. value: 给单选框加上 value 属性,用于提交给后台的数据
      结合 Vue 使用 → v-model
    -->
    性别: 
      <input v-model="gender" type="radio" name="gender" value="1">男
      <input v-model="gender" type="radio" name="gender" value="2">女
      <br><br>

    <!-- 
      前置理解:
        1. option 需要设置 value 值,提交给后台
        2. select 的 value 值,关联了选中的 option 的 value 值
      结合 Vue 使用 → v-model
    -->
    所在城市:
      <select v-model="cityId">
        <option value="101">北京</option>
        <option value="102">上海</option>
        <option value="103">成都</option>
        <option value="104">南京</option>
      </select>
      <br><br>

    自我描述:
      <textarea v-model="desc"></textarea> 

    <button>立即注册</button>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        username: '',
        isSingle: false,
        gender: "2",
        cityId: '102',
        desc: ""
      }
    })
  </script>
</body>
</html>

computed computed property

basic grammar

Concept: based on existing data , a new attribute is calculated . 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 }}

Caching features (improving performance) :
Computed properties cache the calculated results , again using direct read caching,
Dependencies changed, automatically recalculated → and cached again
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 "

Computed property complete writing

The default shorthand for computed properties, which can only be accessed for read, not "modified" .
If you want to "modify" → you need to write the full wording of the computed property .

     

Comprehensive Case- Achievement Case

Statement of needs:
1. Rendering function
2. Delete function
3. Add function
4. Calculate the total score and calculate the average score
<!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>
              <!-- 需求:不及格的标红 -->
              <td :class="{red:item.score < 60}" >{
    
    {item.score}}</td>
              <td><a @click.prevent="del(item.id)" href="#">删除</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: 60 },
            { id: 7, subject: '数学', score: 99 },
            { 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)
          {
            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>

watch listener

basic grammar

Role: monitor data changes , perform some business logic or asynchronous operations.
grammar:
① Simple writing → simple type data, direct monitoring
② Complete writing → add additional configuration items

 

complete writing 

② Complete writing → add additional configuration items
(1) deep: true for deep monitoring of complex types
(2) immediate: true initialization immediately executes the handler method once

 

Guess you like

Origin blog.csdn.net/weixin_73295475/article/details/131631423