Part ONE: Vue usage and examples

1. Meet the Vue

Vue is a lightweight incremental framework that is easy to learn, two-way data binding, component-based development, data and structure separation, virtual DOM, and fast to run. Advantage:

Component-based development can develop functional modules and common modules independently to improve reusability and work efficiency.

Reactive two-way data binding: Vue.js automatically responds synchronously to changes in some data on the page. It’s a data-driven page, and a page can also drive data, often used in forms, where the user inputs and we get the data in the data model.

Single-page applications that refresh pages locally without requesting data and dom with each jump.

Good ecology, rich development tools, a lot of improve efficiency

2.Vue usage – Start by creating an instance

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>vue</title>
  </head>
  <body>
    <div id="app">
      <div>{{name}}</div>
      <! -- V-text syntax is equivalent to v-beard syntax -->
      <div v-text="name"></div>
    </div>
      <! --1. Download and import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
     // 2. Create a Vue instance object
      const vm = new Vue({
     // 3. Tell the Vue instance object that you need to control which area of the interface in the future to mount the Vue instance onto the DOM element whose ID is app
        el: "#app".//4. Specify Vue instance object control area data and put the data into the responsive system
        data: {
          name: "CAI Xukun",}});</script>
  </body>
</html>
Copy the code

Part TWO: Vue related instructions

1. Basic instructions

1.1 v-textv-htmlAnd interpolation syntax

Interpolation: You can insert the specified data into the specified location without parsing the HTML

I’m span will still be displayed like this

V-text is the equivalent of innerText, rendered as text by default. Instead of parsing the HTML, v-text overwrites the original content

123123131

Will only display the value of name in the P TAB

V-html is the equivalent of innerHTML, which you learned in the past. It’s rendered as HTML by default, and it overwrites the content of the tag. With V-HTML, data can be filled into tags for parsing and then inserted into the view layer for display.

<span v-text="msg"></span> <! -- same as below --> <span>{{ msg }}</span>
Copy the code

1.2 v – once the instructions

An instruction that does not require an expression and defines its element or component to be rendered only once, including all of its child nodes. If you do not re-render as the data changes after the first rendering, it will be considered static. It is less useful to get changes directly from the cache

    <div id="app">
    // The original data shows CAI Xukun, the current data shows 333
      <p v-once>Original data: {{name}}</p>
      <p>Current data: {{name}}</p>
    </div>
    <script>
      let vue = new Vue({
        el: "#app".data: {
          name: "CAI Xukun",},mounted() {
          this.name = 3333; }});</script>
Copy the code

1.3 v – cloak instructions

  • 1.Vue data binding process: the interface of unbound data will be presented to the user first, and then THE HTML code after binding data will be generated according to the data in the model and the controlled area, and finally the HTML after binding data will be rendered to the interface.

  • {{message}} {{message}} {{message}} {{message}}} {{message}}} {{message}}} {{message}}}

  • [v-cloak]:{display: None} The default is to hide the unrendered interface until the HTML rendering is generated and then display it again

  • 4. The V-cloak command hides the uncompiled Mustache tag before data rendering and automatically displays elements after data rendering;

[v-cloak] {
  display: none;
}

 <div v-cloak>
  {{ message }}
</div>
Copy the code

2. Conditional render V-if and V-show

2.1 V-if, V-else -if, v-else

  • Use V-if once the condition is not true, the DOM element does not exist.
  • V-if is “true” conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly handled during the switchDestruction and reconstruction.
  • V-if is also lazy: if the condition is false during initial rendering, nothing is done — the conditional block is not rendered until the condition is true for the first time.
  • V-if, V-else -if, v-else if used at the same time must be followed closely;
  • If you judge more than one element at a time, you can use a conditional directive on the outer template tag so that the element is not included in the final render.
  • While rendering, Vue will reuse existing elements as much as possible for efficiency reasons, rather than re-rendering. In this case, the DOM has changed, but the input element is retained. Instead of the placeholder hint, the input element has been reused
  • Unique values that use the key attribute are not reused
    <div id="app">
      <template v-if="this.type==='name'">
        <label>User name:</label>
        <input type="text" placeholder="Please enter user name" key="1" />
      </template>
      <template v-else>
        <label>Email address:</label>
        <input type="text" placeholder="Please enter email address" key="2" />
      </template>
      <button @click="handToggleClick">Switching input types</button>
    </div>
<script>
      let vue = new Vue({
        el: "#app".data: {
          type: "name",},methods: {
          handToggleClick() {
            this.type = this.type === "name" ? "mail" : "name"; ,}}});</script>
Copy the code

2.2 v – show

  • V-show toggles the display and hide of elements depending on whether an expression is true or false, and does not destroy elements. When the expression is false, the element element is addeddisplay:none;Properties.
  • V-show is compiled and retained in the DOM regardless of whether the condition is true or false.
  • V – show does not support<template> The element
  • V-show is used to frequently switch components.

Conclusion:

  • 1. Both v-show and v-if are conditional renderings. If the value is true, it is displayed; if the value is false, it is not displayed.
  • 2. Difference between V-if and V-show

V-if: no element will be created as long as the value is false v-show: no element will be created even if the value is false, but if the value is false, the display of the element will be set to None

  • 3. V-if and V-show application scenarios

V-show is recommended if you need to switch element show and hide frequently in enterprise development, and v-if is not

3. V-bind the data to the attributes of the element

If you want to bind data to an element, you can use {{}}, v-text, or V-html, but if you want to bind data to an attribute of the element, you must use V-bind, so v-bind is specifically used to dynamically bind data to an attribute of the element

3.1 v – bind format

V-bind: attribute name ="Bound data": Attribute name ="Bound data"V-bind: SRC V-bind: href// The assigned data can be any valid JS expression
Copy the code

3.2 V-bind Binds the class name to the element

When v-bind is used for class and style, the result of an expression can be an object or an array in addition to a string.

V-bind bound classes can coexist with regular classes.

By default, V-Bind looks for data in Model. If you want V-Bind to look for class names in style, you must put the class names in an array and enclose them in quotes.

1. Bind class object syntax

The following syntax indicates that the existence of the BGC class depends on whether the value of the data attribute isActive is true or false.

// Class name binding:
 <div id="app" 
 class='static' 
 :class="{ bgc:isActive, fz:true}">1233131</div>
// Data control
 data: {
          isActive: true,},// Of course, computed attributes can also be used when conditions are complex
Copy the code
2. Bind class array syntax
    <div id="app" :class="['bgc',abc,isActive?'bb':'']">1233131</div>
    /* fz */ fz */ fz */ fz */ fz */
    <script>
      let vue = new Vue({
        el: "#app".data: {
          abc: "fz".isActive: true,}});</script>
Copy the code
3. Bind the string syntax of class
    <div id="app" :class="classX">1233131</div>
    <script>
      let vue = new Vue({
        el: "#app".data: {
          classX: {
            bgc: true.fz: true.bb: true,}}});</script>
Copy the code

3.3 V-bind binds styles to elements

If the attribute name contains -, it must be enclosed in quotes

    <div id="app" :style="[styles,{color:color,'font-size':fontSize+'px'}]">
      1233131
    </div>
    <script>
      let vue = new Vue({
        el: "#app".data: {
          color: "red".fontSize: "100".styles: {
            backgroundColor: "blue",}}});Copy the code

3.4 Usage Tips

  • The class name is determined, but not determined, by the object type, and the value is true and false
  • Some classes don’t need to be controlled, some classes need to be controlled by true and false, and the outer layers use arrays, and the controls use objects

4. Bind the v-on method

4.1 v – on grammar

  • 1. The V-ON directive is specifically used to bind elements to listen for events; When the v-ON bound event is triggered, the Vue instance object’s methods are searched for the corresponding callback function.
  • 2. V-on instruction format:
    V-on: indicates the event name ="Callback function name"@ Event name ="Callback function name"
    Copy the code
  • 3. You can pass parameters to the bound callback function, and if you need to pass parameters, the last one is taken as an event object parameter$event
  • 4. If you want to use data in a bound function, you must add this to the data. The name of the directly bound function defaults to the event object as the first argument
  <body>
    <div id="app">
      <button @click=$event ($event)" ">I am a button</button>
    </div>
    <script>
      let vue = new Vue({
        el: "#app".data: {
          gender: "man",},methods: {
          myFn(name, age, e) {
            console.log(this.gender, name, age, e); //man CAI Xukun 22 MouseEvent object,}}});</script>
  </body>
Copy the code

4.2 V-ON event modifier

Use V-ON modifiers in Vue to handle things like event bubbling, event capture, blocking default behavior, etc

.once – Only one callback is triggered

By default, the event callback can be executed repeatedly, as soon as the event is raised. If you want the callback that the event is listening for to be executed only once, you can use the.once modifier

 <button @click.once=$event ($event)" "</button>Copy the code
.prevent – Call event.preventdefault ().

If you want to prevent the default behavior of an element, you can use the.prevent modifier

.stop – Call event.stopPropagation().
  • By default, the download of nested elements triggers event bubbling if they all listen for the same event, and if you want to prevent event bubbling, you can use the.stop modifier.
  • Whoever writes the.stop modifier is not passed on to its parent element
  • If it is written on the father, the son will be passed on to the father, but the father will not be passed on to the grandfather
.self
  • If you want the callback to be executed only when the event is triggered by the current element, you can use the.self modifier
  • If it is not triggered from the current element, it is bound.selfThe elements of the modifier do not participate in the bubble phase and capture
  • Prevents the current element from participating in capture and bubbling, without affecting the parent element.
.capture – Capture mode is used when adding event listeners.
  • The default is event bubbling, and if you want to change to event capture, you need to use the.capture modifier.
  • The trigger process is bound to whom.captureModifier, clicking on the child triggers the modifier, triggers the source event, triggers the one in between, from the parent element to the child element.

.passive

When we are listening for element scroll events, the OnScroll event will be triggered all the time, which is fine on the PC side, but on the mobile side, it will freeze our web page, so when we use this modifier, we are giving the onScroll event a lazy modifier.

<div v-on:scroll.passive="onScroll">... </div>Copy the code
.native
  • To bind some events to a component, you must use the. Native modifier, otherwise they will not fire.
  • The function of the. Native modifier is to convert a VUE component into a normal HTML tag. Using the. Native modifier to manipulate a normal HTML tag invalidates the event
<My-component @click.native="shout(3)"></My-component>
Copy the code

4.3 Other modifiers

Keyup. enter Specifies the keyword modifier
//<! Call 'vm.submit()' only if 'key' is' Enter 'or the corresponding key code.
<input v-on:keyup.enter="submit">
<input type="text" @keyup.keyCode="submit">/ / abandonedCopy the code

Part three: Vue list rendering

1.v-for

The V-for directive is used to render the list of items based on the data source. This directive can be used on template blocks or elements.

The V-for directive requires a special syntax of the form item in Items, where items are the source data array and item is the alias of the array element being iterated over.

An array or object can also be aliased for an index value. An object can also be aliased for a value.

<div v-for="item in items">{{ item }}</div>
<div v-for="(item, index) in items">{{ item }} {{ index }}</div>
<div v-for="val in object"></div>
<div v-for="(val, key) in object"></div>
<div v-for="(val, key, index) in object"></div>
Copy the code

2. Key words

  • When rendering a list using the V-for command, it is common to specify a key attribute for each iteration element. This is because Vue uses the key attribute to create a unique identifier for each iterated element, preventing in-place reuse (that is, if the order of data items is changed, Vue will not move DOM elements to match the order of data items, but will update each element in-place).

  • Explain. If there are any dynamic UI changes in our list (such as the order of list items being scrambled), Vue will choose to change the data in each element rather than move the DOM element accordingly. This is not a problem in most cases. In some cases, however, v-for renders list items that depend on DOM state and/or subcomponent state, which can result in some unexpected rendering effects.

  • For example, if a render template contains a field that allows the user to enter messages directly, the text will unexpectedly match if it is out of order.

3.v-model

  • 1. The V-model directive is used on form control elements (<input>, <textarea> and <select>Create a two-way data binding. It automatically selects the correct method to update the element based on the control type.
  • 2. V-model is essentially a syntactically sugar for input events and V-bind.
 <div id="app">
   <! -- <input type="text" v-model="username" /> -->
   <! The following input box simulates bidirectional binding: using v-bind and input events; Vbind the input event listens for changes in the input box and assigns values to data.
   <input type="text" :value="username" @input="handle" />
 </div>
 <script>
   let vm = new Vue({
     el: "#app".data() {
       return {
         username: ""}; },methods: {
       handle(event) {
         this.username = event.target.value; ,}}});</script>
Copy the code

3.1 V-Model binding text box

      <! -- Single line text -->
      <input type="text" v-model="username" />
      <! -- Multiple lines of text -->
      <textarea v-model="username" placeholder="Please enter multiple lines of text"></textarea>
Copy the code

3.2 V-Model binding check box

  • 1. Single check box, bind Boolean value (select or not toggle Boolean value)
  • 2. Multiple check boxes, multiple check boxes, bind to the same array: check to add value data to the bidirectionally bound array
<div id="app">
  <p>-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the checkBox radio -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --</p>
          <div class="two">
            <label for="agree">
              <input type="checkbox" id="agree" v-model="isAgree" />Agree to a deal</label>
            <p>Your options are :{{isAgree}}</p>
            <button :disabled=! "" isAgree">Next step: Register your email</button>
          </div>
    
 <p>-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the checkBox boxes, -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --</p>
          <div class="three">
            <label for="">
              <input type="checkbox" checked value="Basketball" v-model="hobbies" />basketball
            </label>
            <label for="">
              <input type="checkbox" value="Football" v-model="hobbies" />football 
            </label>
            <label for="">
              <input type="checkbox" value="Badminton"  v-model="hobbies"/>yuMaoball 
            </label>
            <label for="">
              <input type="checkbox" value="Table tennis" v-model="hobbies" />PingPang
            </label>
            <p>Your hobbies are :{{hobbies}}</p>
          </div>
    </div>
    <script>
      let vm = new Vue({
        el: "#app".data() {
          return {
            // checkbox checkbox
          isAgree: false.// checkbox checkbox
          hobbies: [],}; }});</script>
Copy the code

3.3 V-Model Binding radio button

  • Select one and assign its value to the two-way data
    <div id="app">
      <! -- V-model radio -->
      <div class="one">
        <label for="male">
          <input type="radio" id="male" name="sex" value="Male" v-model="sex" />male</label>
        <label for="female">
          <input type="radio" name="sex" value="Female" v-model="sex" />female</label>
        <p>The sex you have chosen is :{{sex}}</p>
      </div>
    </div>
    <script>
      let vm = new Vue({
        el: "#app".data() {
          return {
            // radio
            sex: "Male"}; }});Copy the code

3.4 V-Model Binding Option box

    <div id="app">
      <p>-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the select box when the radio -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --</p>
      <div class="four">
        <select name="abc" id="" v-model="city">
          <option value="Beijing">Beijing</option>
          <option value="Shanghai">Shanghai</option>
          <option value="Shenzhen">shenzhen</option>
          <option value="Guangzhou">Guangzhou</option>
          <option value="Wuhan">wuhan</option>
        </select>
        <p>Your city is :{{city}}</p>
      </div>
      <p>---------------select if ----------------------- is selected</p>
      <div class="five">
        <select name="abcd" id="" v-model="citys" multiple>
          <option value="Beijing">Beijing</option>
          <option value="Shanghai">Shanghai</option>
          <option value="Shenzhen">shenzhen</option>
          <option value="Guangzhou">Guangzhou</option>
          <option value="Wuhan">wuhan</option>
        </select>
        <p>Your city of choice is :{{citys}}</p>
      </div>
    </div>
    <script>
      let vm = new Vue({
        el: "#app".data() {
          return {
            / / select radio
            city: ""./ / select alternative
            citys: [],}; }});</script>
Copy the code

With V – for:

    <div id="app">
      <p>-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the select box when the radio -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --</p>
      <div class="four">
        <select v-model="select">
          <option v-for="option in options" v-bind:value="option.value">
            {{ option.text }}
          </option>
        </select>
        <p>{{select}}</p>
      </div>
      <p>---------------select if ----------------------- is selected</p>
      <div class="five">
        <select name="abcd" id="" v-model="selects" multiple>
          <option v-for="option in options" v-bind:value="option.value">
            {{ option.text }}
          </option>
        </select>
        <p>The selects are :{{selects}}</p>
      </div>
    </div>
    <script>
      let vm = new Vue({
        el: "#app".data() {
          return {
            select: "Shenzhen"./ / select radio
            selects: ["Beijing"."Shanghai"]./ / select alternative
            options: [{text: "beijing".value: "Beijing" },
              { text: "shanghai".value: "Shanghai" },
              { text: "shenzhen".value: "Shenzhen" },
              { text: "guangzhou".value: "Guangzhou" },
              { text: "wuhan".value: "Wuhan"},]}; }});</script>
Copy the code

3.5 Form bidirectional binding modifier

v-model.lazy

With v-Model bidirectional data binding, the bound Model data changes whenever the input field changes, while the lazy modifier updates the data until the cursor leaves the input field.

<input type="text" v-model.lazy="value">
Copy the code
v-model.trim

Function: Filter the beginning and end Spaces in the input box

<input type="text" v-model.trim="value">
Copy the code
v-model.number

If you enter a number first, you can only enter a number. If you enter a string first, you cannot enter a number.

<input type="text" v-model.number="value">
Copy the code

4. Comprehensive usage of list rendering

The

4.1 Render array data

The V-for directive requires special syntax in the form of item in items, which is the source data array and item is the alias of the iteration of the array elements.

Application Scenarios: Usually, to enter an activity, you need to display all the participants, including names, ages, registration dates, etc., and the background must return an ArrayList array, and each element in the array must be an object. How can we efficiently render this array set onto the page? And then get the user ID and go to the next page to query the memberDetail.

<template>
     <div>
         <ul>
             <li v-for="(item,index) in memberList" @click="memberDetail(index)">
                 <span>{{item.custName}}</span>
                 <span>{{item.age}}</span>
                 <span>{{item.joinTime}}</span>
             </li>
         </ul>
     </div>
</template>

<script>
export default {
     created () {
         // Think of it as the user list data that Ajax gets from the background when it initializes entry
         this.memberList = [
            {custName : "ziksang1".age:20.joinTime : "2019-01-02".custId:1},
            {custName : "ziksang2".age:21.joinTime : "2019-01-03".custId:2},
            {custName : "ziksang3".age:22.joinTime : "2019-01-04".custId:3},
            {custName : "ziksang4".age:23.joinTime : "2019-01-05".custId:4},
         ]
     },
     data () {
         return {
             memberList: []}},methods : {
         memberDetail (index) {
             sessionStorage.custId = this.memberList[index].custId
         }
     }
}
</script>
Copy the code

Analysis of the

  • 1. If we use data in the template template, we must declare assignment in the data option first. We give memberList an array of [].
  • 2. In the created function, we simulate the data we get from the background and then assign it to the memberList in the data option. At this point, the memberList has the background value.
  • 3.(item,index) in memberList is a syntactic structure encapsulated by Vue itself

Item represents each element in the collection, in which case each element is an object. Index represents the index of each element in the collection. MemberList is the array to loop through

  • 4. We place (item,index) in memberList on every dom of the loop. That is, the li tag gets all the attributes of the item object only on the li node and all the children of the loop.
  • 5.@click=”memberDetail(index)”, there is a click method, we use index as the parameter of the method, what is the object, this index represents the index of each dom that is loomed out, by clicking, We can get the corresponding user ID, so to speak, any value of each user, and then we can operate in Methods. We can save it in sessonStorage, which can be used to transfer to the next user sentiment page to obtain all user details. We can open Google Browser, and when we click with the mouse, You can find changes in sessionStorage and the whole process is a must for any medium-sized project

4.2V – For Object Rendering

  • You can also use V-for to iterate through an object’s properties.
  • (value,key,index) in memberDetailValue is an attribute. Key is an attribute. Index is the index of each DOM node
  • Application scenario: Show a user details, if the back end to you order, how to correctly convenient display, with the fastest, the most convenient method that is v-for iteration object, in general, show a user details, the background must return a user object to you.
<template>
     <table>
         <template>
            <tr>
                <td v-for="(value,key,index) in memberDetail">{{key}}</td>
            </tr>
            <tr>
                <td v-for="(value,key,index) in memberDetail">{{value}}</td>
            </tr>
         </template>
     </table>
</template>

<script>
export default {
     created () {
        // For example, we get the previous custId and pass it to the background to get user data
        this.memberDetail = {
                 name : 'ziksang'.age : 20.address : "XXXX City, XXX Province".tel : "15921898427"
             }
     },
     data () {
         return {
             memberDetail: {}}}}</script>
<style>
body.html{
    width:100%;
    height:100%
}
.divider{
    width:100%;
    height:1px;
    background:black;
}
</style>
Copy the code

5. Array and new detection

Vue rewrites a number of array prototype methods that manipulate array data to trigger view changes:

  • 1.push()
  • 2.pop()
  • 3.shift()
  • 4.unshift()
  • 5.splice()
  • 6.sort()
  • 7.reverse()

The above methods are: first change the data option artList array, and then synchronize with the new view, these methods are the mutation method

In addition, there are some non-mutating methods that cannot trigger view changes by changing the data option artList Array as in Array.prototype. Manipulating data only returns a new Array, so it does not trigger view updates.

1.filter(), 2.concat(), 3.slice(), 4.map()

Simply reassign the resulting return value to the array in the Data option.

  • Displays filtered/sorted results

Sometimes we want to display a filtered or sorted version of an array without actually changing or resetting the original data. In this case, you can create a calculated property to return a filtered or sorted array.

Part four: Calculating properties and listeners

Principle of use: Watch can do what it can do with computed, but not vice versa. Use computed as much as possible

1. Compute attributes computed

  • If the expression in the template is too long or the logic is too complex, we can use the calculation property, which returns a result through the logical calculation.
  • Computed attributes in computed data cannot be declared in data. Each computed attribute has get/set methods, which are used to obtain and set computed attributes, respectively. By default, only get is available. If you need a set, add it yourself. In addition, set sets properties, not directly modify the calculated properties, but modify its dependencies.
  • A calculated property is essentially a function that performs some function or gets some result; Use it as a data attribute.
  • The calculated attributes have dependent attributes, and when they change, the calculated attributes also change. If no changes are made, the previous values are fetched directly from the cache without rerendering, greatly improving performance.
    <div id="app">
      <div>{{fullName}}</div>
      <div>{{name}}</div>
    </div>
    <script>
      var vue = new Vue({
        el: "#app".data: { firstName: "CAI".lastName: "徐坤" },
        computed: {
          /* firstName/lastName are dependent attributes. When they change, count the attributes name and fullName as well. If the previous value is fetched directly from the cache without change, it will not be re-rendered, greatly improving performance */
          // We can write a function
          name() {
            // Get is automatically called when the value is changed
            return this.firstName + this.lastName;
          },

          
          // Object ()
          fullName: {
            get() {
              // Get is automatically called when the value is changed
              return this.firstName + this.lastName;
            },

            set(val) {
              // Called when the value of the evaluated property is set and the value is saved to val}},}});</script>
Copy the code

Two-way data listening is done in object mode:

    <div id="demo">Last name:<input type="text" placeholder="First Name" v-model="firstName" /><br />Name:<input type="text" placeholder="Last Name" v-model="lastName" /><br />Name 1(one-way):<input type="text" placeholder="Full Name1" v-model="fullName1" /><br />Name 2(two-way):<input type="text" placeholder="Full Name2" v-model="fullName2" /><br />
    </div>
    <! -- The last name changes when you change the first and last names. The last name and first name will not change when changing the name.
    <script>
      let vm = new Vue({
        el: "#demo".data: {
          firstName: "CAI".lastName: "徐坤",},computed: {
          fullName1() {
            console.log("get");

            return this.firstName + "-" + this.lastName;
            // Change the first and last names. However, the first and last names will not be changed
          },
          fullName2: {
            // Change the first and last names.
            get() {
              return this.firstName + "-" + this.lastName;
            },
            // The first and last names are changed
            set(value) {
              console.log(value); //fullName2

              const names = value.split("-");
              this.firstName = names[0];
              this.lastName = names[1]; }},}});</script>
Copy the code

2. Listener Watch

  • 1. The Watch attribute is specially used to monitor data changes. As long as the data changes, the callback method of the corresponding data will be automatically called.
  • 2.Watch monitors route changes. In enterprise development, we can use Watch to determine from which interface the current interface jumps to. Scenario: We fetch the list data once when the component is created, listen for the input box, and fetch the filtered list again every time it changes.
  • 3. Asynchronous operations can be performed in watch.
  • 4. The first parameter in the function is the new parameter, and the second parameter is the old parameter
  • 5. When using watch to monitor data changes, in addition to the handler callback, it also has two parameters:

Deep is set to true to listen for changes in the object’s internal value. Immediate is set to true to trigger a callback immediately with the current value of the expression

  <div id="app">{{fullName}}</div>
    <script>
      var vue = new Vue({
        el: "#app".data: { firstName: "Foo".lastName: "Bar".fullName: "" },

        watch: {
          // The watch callback can be written as a function
          firstName(newValue, oldValue) {
            console.log(111); // First execution

            this.fullName = newValue + "" + this.lastName;
          },
          // The watch callback can be written as an object
          lastName: {
            // The handler function is executed only when the monitoring attribute is changed
            handler(newValue, oldValue) {
              console.log(222); // First execution

              this.fullName = newValue + "" + this.firstName;
              console.log("1111");
            },
            immediate: true.// Let handler execute as soon as it comes in
            deep: true.// Deep monitoring,}}});</script>
Copy the code
    <div id="demo">Last name:<input type="text" placeholder="First Name" v-model="firstName" /><br />Name:<input type="text" placeholder="Last Name" v-model="lastName" /><br />Name 1(one-way):<input type="text" placeholder="Full Name1" v-model="fullName" /><br />
    </div>
    <! -- The last name changes when you change the first and last names. The last name and first name will not change when changing the name.
    <script>
      let vm = new Vue({
        el: "#demo".data: {
          firstName: "CAI".lastName: "徐坤".fullName: CAI - Xu Kun,},watch: {
          firstName: function (value) {
            console.log("First has changed", value);
            this.fullName = value + "-" + this.lastName;
          },
          lastName(){},}}); vm.$watch("lastName".function (value) {
        console.log("Lastname changed", value);

        this.fullName = this.firstName + "-" + value;
      });
Copy the code

Part five: Life Cycle

1.1 What is the life cycle?

The process from creation to destruction of a Vue instance is called the life cycle and generally includes:

Start creating -> initialize data -> compile template -> mount DOM- Render -> update – Render -> destroy and so on

In common terms:

The life cycle is divided into eight processes: before creation, after creation, before mount, after mount, before update, after update, before destroy, and after destroy. For each Vue lifecycle phase, there are lifecycle hook functions that tell you to do something in the current phase.

We will focus on the life cycle of vUE. Here is an outline:

1. Lifecycle methods during creation:

  • BeforeCreate (before initialization bounds)
  • Created (after initializing the interface)
  • BeforeMount (before rendering dom)
  • Mounted (after rendering dom)

2. Runtime lifecycle methods:

  • BeforeUpdate (Before updating data)
  • Updated (after data is updated)

3. Life cycle method during destruction:

  • BeforeDestroy (Before uninstalling components)
  • Destroyed (after uninstalling components)

1.2 Life cycle methods during creation

  • Lifecycle methods can be added during the creation of a VUE instance. These methods are automatically called by the system at certain stages:
  • Remember, this phase is mostly about vUE instancescreateandmount.
  • The created hook function is valid to indicate that the VUE instance has been created, where we can get data (Ajax), compute properties, and listen properties
  • Mounted indicates that the HTML file in the template is mounted to the HTML page. In this case, you can perform some Ajax operations. Mounted is executed only once.
let vue = new Vue({
  beforeCreate: function () {
    /* The value for each new Vue instance can be used for each new Vue instance */ for each new Vue instance */ for each new Vue instance */ for each new Vue instance
  },
  created: function () {
    /* 2. When created is called, the instance is created, which is the first place we can access the data and methods stored in the Vue instance. * /
    console.log("Data and methods are initialized.".this.msg, this.say);// CAI Xukun say()
    console.log("El not associated with #app".this.$el);  //undefined
  },
  beforeMount: function () {
    /* 3. Call beforeMount to indicate that Vue has compiled the final template, but has not yet rendered the final template to the interface. The vue instance's $EL is initialized, but the previously virtual DOM node is still mounted, and data.message has not been replaced. * /
   console.log("El not compiled".this.$el); //
      
...
console.log(document.querySelector("p").innerHTML);//{{msg}} console.log(document.querySelector("p").innerText);//{{msg}} }, mounted: function () { /* When mounted is invoked, Vue completes the template rendering, and data.message is successfully rendered. * / console.log(document.querySelector("p").innerHTML);/ / CAI xu console.log(document.querySelector("p").innerText);/ / CAI xu }, el: "#app".data: { msg: "CAI Xukun",},methods: { say() { console.log("say"); ,}}});Copy the code
Diagram creation stage

1.3 Run-time lifecycle methods

  • BeforeUpdate is triggered when data changes
  • The updated method is triggered when a data-driven interface changes
let vue = new Vue({
  beforeUpdate: function () {
    /* When calling beforeUpdate, the data stored in the Vue instance is modified; BeforeUpdate is called only when the saved data is modified, otherwise it is not called; When calling beforeUpdate, the data is updated, but the interface is not yet updated; * /
  },
  updated: function () {
    /* Updated */ is invoked when the Vue instance's data is updated and the interface is synchronized}});Copy the code

1.4 Life cycle method during destruction

 beforeDestroy: function(){
    /* When calling beforeDestroy, the current component is about to be destroyed. BeforeDestroy is not called as long as the component is not destroyed. BeforeDestroy is the last function we have access to component data and methods. This step typically does some resetting, such as clearing timers and listening dom events */ from the component
        },
 destroyed: function(){
      Note: as long as the component is not destroyed, the destroyed method does not operate on data and methods in the component */
            console.log("destroyed");
        }
Copy the code

1.5 Component life cycle

  • 1.Vue instance object can be regarded as a large component, and our custom component can be regarded as a small component

  • 2. Properties and methods that can be used in a large component can also be used in a small component

  • 3. For example, if you can add data and methods to a Vue instance, you can also add data and methods to a custom component, so you can use lifecycle methods in a Vue instance and lifecycle methods in a component

1.6 Complete life cycle diagram

【 Note 】 See the following in the next article

Part six: Vue component basics

Part 7: Custom directives and filters

Part 8: Rendering functions and JSX syntax

Part nine: Transitions in Vue

Part 10: Vue-Router

Part 11: VueX

Part twelve: Vue- CLI