[Vue3 Knowledge Lecture 4] Detailed explanation of two-way data binding, event binding, and event modifiers

1. Two-way data binding

What is two-way data binding?

  • When the data changes, the view will change accordingly
  • When the view changes, the data will also change accordingly

Digital management platform
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
permission system-Mall
personal blog address

Two-way binding instructions

​ The v-model directive implements two-way data binding

Two-way binding usage scenarios

​ Use the v-model directive to limit the use in input select textarea components (components)

Example:
Insert image description here
modifier

  • .lazy By default, the v-model will update the data after each input event (except for the state of the spelling phase of the IME). You can add the lazy modifier to update the data after each change event instead
  • .number If you want user input to be automatically converted to a number, you can add the .number modifier after the v-model to manage the input
  • .trim If you want to automatically remove the spaces at both ends of the user input by default, you can add the .trim modifier after v-model
<div><input type="text" v-model.lazy="data"></div>
<div><input type="text" v-model.number.trim="numData" @change="checkType"></div>

2. Detailed explanation of event binding

2.1 Event binding instructions in Vue

  • v-on directive usage

    <button v-on:click="fn">v-on</button>
    
  • Directives can be abbreviated as @ (syntactic sugar)

    <button @click="fn2">@语法糖</button>
    

2.2 How to call the event function

  • Bind function name directly

    <button v-on:click="fn">v-on</button>
    
  • Call functions

    <button v-on:click="fn()">v-on</button>
    

2.3 Event function parameter passing

  • Common parameters: Multiple parameters are separated by commas

    <button v-on:click="fn(10,20,30)">v-on</button>
    
  • Event object:

    tip1: If the event is directly bound to the function name or the function is called without passing any parameters, the event function will pass the event object as the first parameter by default;

    tip2: If parameters are passed when the event binding function is called, the event object must be passed explicitly as the last parameter, and the name of the event object must be $event

    tip3: If compatibility issues are not considered and the existence of the window global object is allowed, the event object window.event can be obtained directly through the global object in the function. It is recommended to use the parameter passing method.

  • Small case: Shopping cart simple counter
    Insert image description here
    Implementation ideas:

  1. Define the initial number num in data
  2. Set num to the corresponding label using "interpolation expression" or "v-text directive"
  3. Use the v-on directive to define click events add and reduce for the add and subtract buttons.
  4. Define the logic of add and reduce methods in methods: the minimum number is 1 and the maximum number is 20

3. Event modifiers

3.1 Commonly used event modifiers in Vue

  • .stop stops bubbling

  • .prevent cancels the default event

  • .self event handler will only be fired if event.target is the element itself

  • capture.capture Use capture mode when adding event listeners

  • The .once event is fired at most once

  • The .passive modifier is generally used in touch event listeners and can be used to improve the scrolling performance of mobile devices. Cannot be used with .prevent.

    // 通过 .stop 修饰符阻止事件冒泡行为
    <div class="out" @click="fn2">
        外部容器
        <div class="in" @click.stop="fn">内部容器</div>
    </div>
    
    //通过 .prevent 修饰符阻止 a 标签默认跳转功能
    <a href="http://www.baidu.com" @click.prevent="cancel">跳转百度</a>
    
    //链式修改
    <a @click.stop.prevent="doThat"></a>
    

3.2 Key modifiers

  • .enter => enter key

  • .tab => tab key

  • .delete (captures "delete" and "backspace" keys) => delete key

  • .esc => Cancel key

  • .space => space bar

  • .up => up

  • .down => down

  • .left => left

  • .right => right

    // .enter 回车键
    <div class="login">
          <p><label>用户名:<input type="text" v-model="username" placeholder="请输入用户名"></label></p>
          <!-- 按键修饰符 .enter 触发回车键 -->
          <p><label>密码:<input type="password" v-model="password" placeholder="请输入密码" @keyup.enter="login"></label></p>
          <button @click="login">登录</button>
      </div>
      
    // .delete 删除建
    <input @keyup.delete='submit'/>
    

4. Attribute binding

The v-bind directive is used to update HTML attributes responsively

Syntax v-bind:prop = val

Syntactic sugar: prop = val

//属性绑定
<h2 v-bind:title="title">属性绑定演示</h2>
<p :class="ft20">语法糖</p>
<div v-bind="{id:‘container’,class:'wrapper'}"></div>

Note: Syntax sugar is a simplification of a certain operation to improve development efficiency.

5. Binding of classes and styles

5.1 Class binding

  • Binding object syntax

    v-bind:class = { class name: class value, class name 1: class value 1,..., class name n: class value n }

    If the value corresponding to the class name is true, the class name is displayed; otherwise, the class name is not displayed.

  • Bind array syntax

    v-bind:class = [value1, value2,…, valuen]

    Value 1 and value 2 correspond to the data in data

    <script setup>
    import {
          
           ref, reactive, computed } from 'vue'
    
    const clsName = "active-link"
    // 通过 ref 声明的数据,在 script 中,需要通过 .value 获取和修改值;在 template 模板中使用时,则不需要通过 .value 获取值,模板会自动解析数据
    const count = ref(0)
    
    // 注意:这里如果想要在count值修改后,实时响应数据变化,需要采用计算属性
    const clsObj = computed(() => ({
          
          
        link: true,
        activeLink: count.value % 2 == 0
    }))
    
    let fm = ref(true)
    </script>
    <template>
        <div>
            <!-- 基于 v-bind 指令,增强绑定 class类 与 style样式,这两个属性值除了可以使用字符串外,还可以使用对象和数组的绑定 -->
            <a href="javascript:;" :class="clsName" class="link" style="text-decoration:none;"
                :style="'font-style:italic;'">超链接标签演示字符串类型的class和style绑定</a>
            <hr>
            <a href="javascript:;" :class="clsObj"
                :style="{ 'text-decoration': 'none', fontStyle: count % 2 == 0 ? 'italic' : '' }">采用绑定对象的方式实现class和style的赋值</a>
            <hr>
            <a href="javascript:;" :class="['link', 'active-link', { fm }]"
                :style="['letter-spacing:6px;', { 'text-decoration': 'none', fontStyle: count % 2 == 0 ? 'italic' : '' }]">采用数组绑定的方式实现class和style</a>
        </div>
        <button @click="count++">count++</button>
    </template>
    
    <style scoped>
    hr {
          
          
        margin: 2vh 0;
    }
    
    .link {
          
          
        color: gray;
    }
    
    .active-link,
    .activeLink {
          
          
        font-weight: bold;
    }
    
    .fm {
          
          
        font-family: "楷体";
    }
    </style>
    

5.2 style style binding

  • Binding object syntax

    v-bind:style = { style name: style value, style name 1: style value 1,..., style name n: style value n }

  • Bind array syntax

    v-bind:style = [value 1, value 2, …, value n]

    Value 1, value 2,..., value n need to use objects in data to define styles and style values.

    <script setup>
    import {
          
           ref, reactive, computed } from 'vue'
    
    const clsName = "active-link"
    // 通过 ref 声明的数据,在 script 中,需要通过 .value 获取和修改值;在 template 模板中使用时,则不需要通过 .value 获取值,模板会自动解析数据
    const count = ref(0)
    
    // 注意:这里如果想要在count值修改后,实时响应数据变化,需要采用计算属性
    const clsObj = computed(() => ({
          
          
        link: true,
        activeLink: count.value % 2 == 0
    }))
    
    let fm = ref(true)
    </script>
    <template>
        <div>
            <!-- 基于 v-bind 指令,增强绑定 class类 与 style样式,这两个属性值除了可以使用字符串外,还可以使用对象和数组的绑定 -->
            <a href="javascript:;" :class="clsName" class="link" style="text-decoration:none;"
                :style="'font-style:italic;'">超链接标签演示字符串类型的class和style绑定</a>
            <hr>
            <a href="javascript:;" :class="clsObj"
                :style="{ 'text-decoration': 'none', fontStyle: count % 2 == 0 ? 'italic' : '' }">采用绑定对象的方式实现class和style的赋值</a>
            <hr>
            <a href="javascript:;" :class="['link', 'active-link', { fm }]"
                :style="['letter-spacing:6px;', { 'text-decoration': 'none', fontStyle: count % 2 == 0 ? 'italic' : '' }]">采用数组绑定的方式实现class和style</a>
        </div>
        <button @click="count++">count++</button>
    </template>
    
    <style scoped>
    hr {
          
          
        margin: 2vh 0;
    }
    
    .link {
          
          
        color: gray;
    }
    
    .active-link,
    .activeLink {
          
          
        font-weight: bold;
    }
    
    .fm {
          
          
        font-family: "楷体";
    }
    </style>
    

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/132620218