Vue2.0 modifiers, binding styles, computed properties and listener properties

1. Modifier

1. Event modifier: The event modifier handles the event capture and target (syntax: @event name. modifier)

(1) stop: prevents the event from bubbling, which is equivalent to calling the event.stopPropagation method

(2) prevent: Prevent the default behavior of the event, which is equivalent to calling the event.preventDefault method

(3) self: trigger only when event.target is the current element itself

(4)once: The bound event can only be triggered once

(5) capture: Let the event trigger trigger from the top-level development containing this element to the bottom (that is, the capture mode)

(6) passive: The default behavior of the event is executed immediately, without waiting for the event callback

(7) native: Let the component listen to the native event of the root element like a built-in HTML tag, otherwise v-on on the component will only listen to custom events

Note: When using modifiers, order is important; the corresponding code will be generated in the same order.

Thus,Using v-on:click.prevent.self will prevent all clicks, while v-on:click.self.prevent will only prevent clicks on the element itself

2. Keyboard modifiers: Keyboard modifiers are used to modify keyboard events (such as: onkeyup, onkeydown, etc.), and keyboard event triggers require corresponding keyCode. However, there are many keyCode, so for the convenience of use, Vue provides us with an alias modifier

(1) Common keys (enter, delete, space, tab, esc…)

(2) System modifier keys (ctrl, shift, alt…)

(3) You can also directly use the key code as a modifier (for example: enter is 13)

3. Form modifier: This modifier is mainly used in the common commands of the form, and v-model modifies the input content of the form.

(1) lazy: lazy is similar to lazy loading. When we fill in the information on the form, it will not trigger the change of the v-model value. It will only be assigned when the cursor leaves

(2) trim: filter out the spaces before and after the input content

(3) number: The input value will be converted to a numeric type

2. Binding styles

class and style are the attributes of HTML elements, which are used to set the style of elements. We can use v-bind to set style attributes. Vue.js v-bind specifically enhances it when dealing with class and style. The result type of an expression can be an object or an array in addition to a string.

Code sample:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Binding styles</title>
<style>
.basic{
width: 300px;
height: 50px;
border: 1px solid black;
}
.happy{
border: 3px solid red;;
background-color: rgba(215, 235, 0, 0.54);
background: linear-gradient(30deg,yellow,pink,orange,yellow);
}
.sad{
border: 4px dashed rgb(2, 197, 2);
background-color: gray;
}
.normal{
background-color: skyblue;
}
.atguigu1{
background-color: yellowgreen;
}
.atguigu2{
font-size: 30px;
text-shadow: 2px 2px 10px red;
}
.atguigu3{
border-radius: 20px;
}
</style>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<!-- Binding class style--string writing method, applicable to: the class name of the style is uncertain and needs to be specified dynamically -->
<div class="basic" :class="mood" @click="changeMood">{<!-- -->{name}}</div> <br/><br/>

<!-- Binding class style--array writing method, applicable to: the number of styles to be bound is uncertain, and the name is also uncertain -->
<div class="basic" :class="classArr">{<!-- -->{name}}</div> <br/><br/>

<!-- Binding class style--object writing method, suitable for: the number of styles to be bound is determined, and the name is also determined, but it is necessary to dynamically decide whether to use -->
<div class="basic" :class="classObj">{<!-- -->{name}}</div> <br/><br/>

<!-- Binding style style -- object writing -->
<div class="basic" :style="styleObj">{<!-- -->{name}}</div> <br/><br/>
<!-- Binding style style -- array writing -->
<div class="basic" :style="styleArr">{<!-- -->{name}}</div>
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
\t\t
const vm = new Vue({
el:'#root',
data:{
name:'VUE',
mood:'normal',
classArr:['atguigu1','atguigu2','atguigu3'],
classObj: {
atguigu1: false,
atguigu2: false,
},
styleObj: {
fontSize: '40px',
color:'red',
},
styleObj2: {
backgroundColor:'orange'
},
styleArr:[
{
fontSize: '40px',
color:'blue',
},
{
backgroundColor:'gray'
}
]
},
methods: {
changeMood(){
const arr = ['happy','sad','normal']
const index = Math. floor(Math. random()*3)
this. mood = arr[index]
}
},
})
</script>
</html>

1.class style of writing: class=”xxx” xxx can be a string, an object, or an array.

(1) The string writing method is suitable for: the class name is uncertain and must be obtained dynamically.

(2) The object writing method is suitable for: to bind multiple styles, the number is uncertain, and the name is also uncertain.

(3) The array writing method is suitable for: to bind multiple styles, the number is determined, and the name is also determined, but it is not sure whether to use it or not.

2.style Style writing: style=”{fontSize: xxx}” where xxx is a dynamic value. :style=”[a,b]” where a and b are style objects.

3. Computed property

1. Grammar

(1) Normal writing:

computde: {
    fullName: {
        get() {
            //Execute code depending on data changes
        }
        set() {
            //The calculated attribute value is modified to execute the code
        }
    }
}

(2) Shorthand: only use the getter and not the setter to use the shorthand method

computde: {
    fullName() {
         //Execute code depending on data changes
    }
}

2.computed description

(1) The monitoring value is not defined in data, in the form of return return value;

(2) Calculated attribute variables are defined in computed, and attribute monitors are defined in data.

(3) Computed properties can only be read by get by default. When manually modifying a calculated property, a handwritten set function will be triggered.

(4) The value of the computed attribute will be cached, and it will be recalculated only when the related dependency value in the instance changes. It has good performance but is not suitable for asynchronous requests.

(5) A computed property is a declarative description that a value depends on other values, and the DOM is updated with the recalculated result after the dependent value changes. The property monitors the defined variable, and when the defined value changes, the corresponding function is executed.

3.computed usage description

(1) All kinds of complex logic can be completed in a computed property, including operations, function calls, etc., as long as a result is finally returned.

(2) The computed property can also depend on the data of multiple Vue instances. As long as any of the data changes, the computed property will be re-executed and the view will be updated.

4.computed [getter and setter]

(1) Computed properties have two methods: getter setter is used to realize two-way binding of data

(2) Each computed property contains a getter and a setter. When you need it, you can also provide a setter function. When manually modifying the value of a computed property is like modifying an ordinary data, the setter will be triggered function, perform some custom operations
(3) Computed properties are often used to dynamically set the style name class and inline style style of elements

4. Listen attribute (watch)

1. Definition of watch: watch is an observation action. It can listen to the change of the attribute value (data/computed) of the specified name. Once the attribute value changes, the listener will be triggered, and then the listener Execute the corresponding business code

(1) Listeners are generally used to monitor data changes, and are executed by default when data changes.

(2) The monitored data name is put here as the function name. There are two parameters in this function, one is the new value and the other is the old value.

(3) In vue, use watch to respond to data changes

2. Simple listening (mainly for variables and simple data types)

(1) watch is a separate configuration item in vue

(2) The function name in the watch must be consistent with the attribute name, and cannot be called manually

(3) There is no return value. If you want to use the processing result, you must assign the result to a member in data before using it.

<template>
  <div>
    <input type="text" v-model="name">
  </div>
</template>
<script>
export default {
  data(){
    return {
      name: ""
    }
  },
  // Goal: Listen to the change of name value
  watch: {
    // newVal: the current latest value oldVal: the value at the last moment
    name(newVal, oldVal){
      console.log(newVal, oldVal); //It is automatically triggered when the corresponding value of the variable name changes
    }
  }
}
</script>

3. Deep listening (mainly for complex data types or listening functions that need to be executed immediately)

(1) handler: fixed method trigger. The listening function must be called handler (required)

(2) deep: Enable deep listening (required)

(3)immediate: listen immediately (the handler is executed immediately when the page is initialized)

<template>
  <div>
    <input type="text" v-model="user.name">
    <input type="text" v-model="user.age">
  </div>
</template>
 
<script>
export default {
  data(){
    return {
      user: {
        name: "",
        age: 0
      }
    }
  },
  // target: listener object
  watch: {
        // The first type: monitor the entire object, and each property value change in the object will execute the handler
        // Note: After the attribute value changes, the value of newVal obtained after the handler is executed is the same as the value of oldVal
    user: {
      handler(newVal, oldVal){
        console.log(newVal, oldVal);
      },
      deep: true, // deep listening for changes in complex types
      immediate: true // execute immediately
    }
  }
// Goal: Listen to a value in the object precisely
 watch: {
       // The second way: monitor an attribute of the object, and the function will be executed when the value of the monitored attribute changes
       // After the function is executed, the obtained newVal value is different from the oldVal value
    'user.name': {
      handler(newVal, oldVal){
        console.log(newVal, oldVal);
      },
      deep: true, // deep listening for changes in complex types
      immediate: true // execute immediately
    }
  }
}
</script>