Front end frame VUE

Posted by Zephyris on Sat, 22 Jan 2022 09:13:27 +0100

1,VUE

1.1 general

Vue is a front-end framework that eliminates DOM operations in native JavaScript and simplifies writing.

We have also learned the back-end framework mybatis before. Mybatis is used to simplify jdbc code writing; VUE is the front-end framework, which is used to simplify JavaScript code writing. The day before yesterday, we made a comprehensive case in which a large number of DOM operations were carried out, as follows

After learning VUE, we don't need to write this part of code. So how does VUE simplify DOM writing?

==Based on the idea of MVVM (model view view model), the two-way binding of data is realized, and the programming focus is on the data== Before, we focused on DOM operation; To understand the idea of MVVM, we must first talk about the idea of MVC, as shown in the figure below

C is our js code, M is the data, and V is the content displayed on the page. As shown in the figure below, we wrote the code before

The idea of MVC can't bind in both directions. Two way binding means that when the data model data changes, the page display will change. If the form data changes, the bound model data will also change. Next, let's talk about the idea of MVVM. As shown in the figure below, there are three component diagrams

The model in the figure is our data, the View is the View, that is, the page label, and the content that users can see through the browser; Model and View are bound Bi directionally through ViewModel objects, which are provided by Vue. Next, let's take a look at the effect of two-way binding. The following figure is the code prepared in advance. The input box binds the username model data, and {}} is also used to bind the username model data on the page

Open this page through the browser and you can see the following pages

When we enter content in the input box, and the content we enter is displayed in real time behind the input box, this is the effect of two-way binding.

1.2 quick start

Vue is relatively simple to use. It is divided into the following three steps:

  1. Create a new HTML page and introduce Vue JS file

    <script src="js/vue.js"></script>
    
  2. In the JS code area, create Vue core objects for data binding

    new Vue({
        el: "#app",
        data() {
            return {
                username: ""
            }
        }
    });
    

    When creating a Vue object, you need to pass a js object, and the following attributes are required in the object:

    • el: used to specify which tags are managed by Vue. The app in the attribute value #app needs to be the id attribute value of the managed tag
    • Data: used to define the data model
    • methods: used to define functions. We'll use this later
  3. Authoring views

    <div id="app">
        <input name="username" v-model="username" >
        {{username}}
    </div>
    

    {{}} is the interpolation expression defined in Vue, in which the data model is written. At that time, the data value of the model will be displayed in this position.

The overall code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <input v-model="username">
    <!--Interpolation expression-->
    {{username}}
</div>
<script src="js/vue.js"></script>
<script>
    //1. Create Vue core object
    new Vue({
        el:"#app",
        data(){  // data() is a new way of writing ECMAScript version 6
            return {
                username:""
            }
        }

        /*data: function () {
            return {
                username:""
            }
        }*/
    });

</script>
</body>
</html>

1.3 Vue instruction

**Instructions: * * special attributes with v-prefix on HTML tags. Different instructions have different meanings. For example: v-if, v-for

Common instructions are:

instructionseffect
v-bindBind attribute values for HTML tags, such as setting href, CSS style, etc
v-modelCreate a two-way data binding on a form element
v-onBinding events for HTML tags
v-ifConditionally render an element. Render when it is determined to be true, otherwise it will not be rendered
v-else
v-else-if
v-showAn element is displayed according to conditions. The difference is that the value of the display attribute is switched
v-forList rendering, traversing the elements of the container or the attributes of the object

Next, let's learn these instructions one by one

1.3.1 v-bind & V-model instruction

  • v-bind

    This instruction can bind model data to the original attributes of the tag. In this way, when the model data changes, the tag attribute value also changes

    For example:

    <a v-bind:href="url">use Baidu Search</a>
    

    The above v-bind: "can be simplified as follows:

    <!--
    	v-bind Can be omitted
    -->
    <a :href="url">use Baidu Search</a>
    
  • v-model

    This instruction can bind model data to form item labels. In this way, the bidirectional binding effect can be realized. For example:

    <input name="username" v-model="username">
    

Code demonstration:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <a v-bind:href="url">Click</a>
    <a :href="url">Click</a>
    <input v-model="url">
</div>

<script src="js/vue.js"></script>
<script>
    //1. Create Vue core object
    new Vue({
        el:"#app",
        data(){
            return {
                username:"",
                url:"https://www.baidu.com"
            }
        }
    });
</script>
</body>
</html>

Open the above page through the browser and check the path of the hyperlink. The path will change according to the path entered in the input box, because the hyperlink and the input box are bound to the same model data

1.3.2 v-on instruction

We define a button on the page and bind the click event with the v-on instruction. The html code is as follows

<input type="button" value="A button" v-on:click="show()">

When using v-on, you can also use a simplified writing method to replace v-on: with @. The html code is as follows

<input type="button" value="A button" @click="show()">

The show() bound by the above code needs to be defined in the methods attribute of the Vue object

new Vue({
    el: "#app",
    methods: {
        show(){
            alert("I was ordered");
        }
    }
});

Note: v-on: the following event name is the previous native event attribute name, with on removed.

For example:

  • Click event: the event attribute name is onclick, while v-on:click is used in vue
  • Loss of focus event: the event attribute name is onblue, and when used in vue, v-on: blue

The overall page code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <input type="button" value="A button" v-on:click="show()"><br>
    <input type="button" value="A button" @click="show()">
</div>
<script src="js/vue.js"></script>
<script>
    //1. Create Vue core object
    new Vue({
        el:"#app",
        data(){
            return {
                username:"",
            }
        },
        methods:{
            show(){
                alert("I was ordered...");
            }
        }
    });
</script>
</body>
</html>

1.3.3 condition judgment instruction

Next, let's demonstrate it through code. Define a count data model in Vue, as follows

//1. Create Vue core object
new Vue({
    el:"#app",
    data(){
        return {
            count:3
        }
    }
});

Now, when the data of the count model is 3, div1 content is displayed on the page; When the data of count model is 4, div2 content is displayed on the page; When the count model data is other values, div3 is displayed on the page. Here, in order to dynamically change the value of the model data count, an input box is defined to bind the count model data. The html code is as follows:

<div id="app">
    <div v-if="count == 3">div1</div>
    <div v-else-if="count == 4">div2</div>
    <div v-else>div3</div>
    <hr>
    <input v-model="count">
</div>

The overall page code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <div v-if="count == 3">div1</div>
    <div v-else-if="count == 4">div2</div>
    <div v-else>div3</div>
    <hr>
    <input v-model="count">
</div>

<script src="js/vue.js"></script>
<script>
    //1. Create Vue core object
    new Vue({
        el:"#app",
        data(){
            return {
                count:3
            }
        }
    });
</script>
</body>
</html>

Open the page through the browser and enter different values in the input box. The effect is as follows

Then let's look at the effect of the v-show instruction. If the value of the model data count is 3, the div v-show content will be displayed. Otherwise, it will not be displayed. The html page code is as follows

<div v-show="count == 3">div v-show</div>
<br>
<input v-model="count">

The browser opens as follows:

Through the above demonstration, it is found that the effects of v-show and v-if are the same. What are the differences between them? We check the source code according to the browser's check function

It can be seen from the above figure that the principle of v-show is to add the display css attribute to the corresponding tag and set the attribute value to none, so as to achieve the effect of hiding. The v-if instruction does not render when the conditions are not met.

1.3.4 v-for instruction

This instruction is used for traversal when you see its name. The format of this instruction is as follows:

<label v-for="Variable name in Aggregate model data">
    {{Variable name}}
</label>

Note: if you need to loop that label, the v-for instruction is written on that label.

If you need to use the index of the collection model data on the page, you need to use the following format:

<label v-for="(Variable name,Index variable) in Aggregate model data">
    <!--The index variable starts from 0, so to represent the sequence number, you need to manually add 1-->
   {{Index variable + 1}} {{Variable name}}
</label>

Code demonstration:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <div v-for="addr in addrs">
        {{addr}} <br>
    </div>

    <hr>
    <div v-for="(addr,i) in addrs">
        {{i+1}}--{{addr}} <br>
    </div>
</div>

<script src="js/vue.js"></script>
<script>

    //1. Create Vue core object
    new Vue({
        el:"#app",
        data(){
            return {
                addrs:["Beijing","Shanghai","Xi'an"]
            }
        }
    });
</script>
</body>
</html>

The effect of opening through the browser is as follows

1.4 life cycle

The eight stages of the life cycle: each time a life cycle event is triggered, a life cycle method will be automatically executed. These life cycle methods are also called hook methods.

The following figure shows the whole process from creating Vue to effect Vue objects and the hook functions corresponding to each stage provided on the Vue official website

See the above figure, you don't need to pay too much attention to this figure. For these hook methods, we only focus on mounted.

mounted: mount is completed, Vue initialization is successful, and HTML page rendering is successful. In the future, we will send asynchronous requests and load data in this method.

1.5 cases

1.5.1 requirements

Use Vue to simplify the brand list data query and addition function we did after learning ajax the day before

This case only uses Vue to optimize the front-end code, and the back-end code does not need to be modified.

1.5.2 query all functions

  1. At brand js file introduced into vue by HTML page

    <script src="js/vue.js"></script>
    
  2. Creating Vue objects

    • Define model data in Vue objects
    • Send the asynchronous request in the hook function and assign the data of the response to the data model
    new Vue({
        el: "#app",
        data(){
            return{
                brands:[]
            }
        },
        mounted(){
            // After the page is loaded, send an asynchronous request to query the data
            axios({
                method:"get",
                url:"http://localhost:8080/brand-demo/selectAllServlet"
            }).then(resp=> {
                this.brands = resp.data;
            })
        }
    })
    
  3. Modify view

    • Define < div id = "app" > < / div >, and specify that the div tag is managed by Vue

    • Copy all the contents in the body tag as the div tag above

    • Delete the redundant data rows of the table, leaving only one

    • Use the v-for instruction to iterate over the data rows in the table

      <tr v-for="(brand,i) in brands" align="center">
          <td>{{i + 1}}</td>
          <td>{{brand.brandName}}</td>
          <td>{{brand.companyName}}</td>
          <td>{{brand.ordered}}</td>
          <td>{{brand.description}}</td>
          <td>{{brand.statusStr}}</td>
          <td><a href="#">modify</a> <a href="#"> delete</a></td>
      </tr>
      

The overall page code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <a href="addBrand.html"><input type="button" value="newly added"></a><br>
    <hr>
    <table id="brandTable" border="1" cellspacing="0" width="100%">
        <tr>
            <th>Serial number</th>
            <th>Brand name</th>
            <th>Enterprise name</th>
            <th>sort</th>
            <th>Brand introduction</th>
            <th>state</th>
            <th>operation</th>
        </tr>
        <!--
            use v-for ergodic tr
        -->
        <tr v-for="(brand,i) in brands" align="center">
            <td>{{i + 1}}</td>
            <td>{{brand.brandName}}</td>
            <td>{{brand.companyName}}</td>
            <td>{{brand.ordered}}</td>
            <td>{{brand.description}}</td>
            <td>{{brand.statusStr}}</td>
            <td><a href="#">modify</a> <a href="#"> delete</a></td>
        </tr>
    </table>
</div>
<script src="js/axios-0.18.0.js"></script>
<script src="js/vue.js"></script>

<script>
    new Vue({
        el: "#app",
        data(){
            return{
                brands:[]
            }
        },
        mounted(){
            // After the page is loaded, send an asynchronous request to query the data
            var _this = this;
            axios({
                method:"get",
                url:"http://localhost:8080/brand-demo/selectAllServlet"
            }).then(function (resp) {
                _this.brands = resp.data;
            })
        }
    })
</script>
</body>
</html>

1.5.3 adding functions

The page operation effect is as follows:

The overall process is as follows

Note: the key point of the front-end code is to use the v-model instruction to bind model data to the tag item, and use the two-way binding feature to submit data when sending asynchronous requests.

  1. At addbrand js file introduced into vue by HTML page

    <script src="js/vue.js"></script>
    
  2. Creating Vue objects

    • Define model data brand in Vue object
    • Define a submitForm() function to provide binding for the submit button
    • Send an ajax request in the submitForm() function and pass the model data brand as a parameter
    new Vue({
        el: "#app",
        data(){
            return {
                brand:{}
            }
        },
        methods:{
            submitForm(){
                // Send ajax request, add
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-demo/addServlet",
                    data:this.brand
                }).then(resp=> {
                    // Judge whether the response data is success
                    if(resp.data == "success"){
                        location.href = "http://localhost:8080/brand-demo/brand.html";
                    }
                })
    
            }
        }
    })
    
  3. Modify view

    • Define < div id = "app" > < / div >, and specify that the div tag is managed by Vue

    • Copy all the contents in the body tag as the div tag above

    • Bind model data to each form item label. Finally, the data is encapsulated in the brand object

      <div id="app">
          <h3>Add brand</h3>
          <form action="" method="post">
              Brand name:<input id="brandName" v-model="brand.brandName" name="brandName"><br>
              Enterprise name:<input id="companyName" v-model="brand.companyName" name="companyName"><br>
              Sort:<input id="ordered" v-model="brand.ordered" name="ordered"><br>
              Description information:<textarea rows="5" cols="20" id="description" v-model="brand.description" name="description"></textarea><br>
              Status:
              <input type="radio" name="status" v-model="brand.status" value="0">Disable
              <input type="radio" name="status" v-model="brand.status" value="1">Enable<br>
      
              <input type="button" id="btn" @click="submitForm" value="Submit">
          </form>
      </div>
      

The overall page code is as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Add brand</title>
</head>
<body>
<div id="app">
    <h3>Add brand</h3>
    <form action="" method="post">
        Brand name:<input id="brandName" v-model="brand.brandName" name="brandName"><br>
        Enterprise name:<input id="companyName" v-model="brand.companyName" name="companyName"><br>
        Sort:<input id="ordered" v-model="brand.ordered" name="ordered"><br>
        Description information:<textarea rows="5" cols="20" id="description" v-model="brand.description" name="description"></textarea><br>
        Status:
        <input type="radio" name="status" v-model="brand.status" value="0">Disable
        <input type="radio" name="status" v-model="brand.status" value="1">Enable<br>

        <input type="button" id="btn" @click="submitForm" value="Submit">
    </form>
</div>
<script src="js/axios-0.18.0.js"></script>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el: "#app",
        data(){
            return {
                brand:{}
            }
        },
        methods:{
            submitForm(){
                // Send ajax request, add
                axios({
                    method:"post",
                    url:"http://localhost:8080/brand-demo/addServlet",
                    data:this.brand
                }).then(resp=> {
                    // Judge whether the response data is success
                    if(resp.data == "success"){
                        location.href = "http://localhost:8080/brand-demo/brand.html";
                    }
                })
            }
        }
    })
</script>
</body>
</html>

Through the above optimization, the front-end code is indeed simplified a lot. But the page is still not very good-looking. Next, let's learn Element, which can beautify the page.

Topics: Front-end