This is the 17th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

No road taken in vain, every step counts

Vue & jQuery

  • The position of jquery is to get the element to complete the effect
  • Vue is positioned to facilitate the operation and control of data to complete special effects

Introduce the VUE

Vue.js is the most popular tool library for front-end Web development. It was released by Yu Yuxi in February 2014.

Another common tool library: react. Js/Angular.js /jQuery

Official Website:

English: cn.vuejs.org/

English: vuejs.org/

Official document: cn.vuejs.org/v2/guide/

Vue.js is currently available in 1.x, 2.x and 3.x versions. Let’s study the 2.x version.

Vue has two development modes

  • Scripted import (vue.js file in the project root directory)
<script src="vue.js"></script>
Copy the code
  • Componentized development, DRF componentized development

Vue Basic use

  • Basic usage Steps
1. Import vue.js file in the head tag -- scriptatively<script src='vue.js'></script>2. Create a label and set an ID for it<div id='app'><div>Var vm = new vue (); var vm = new vue (); Data var VM = new vue ({el:'#app', data:{data variable :' variable value ', data:{data variable :' variable value ', Message :' ha ha ',},}) el: sets the range of HTML content that vue can manipulate. The value is usually the CSS ID selector. Data: stores the data in the Vue object to be displayed on the HTML page<div id='app'>
            {{message}}
        </div>
Copy the code
  • Matters needing attention
When instantiating vue objects, each object name must be unique, a page has multiple Vue objects, each object corresponds to a function 2Copy the code

The framework of VUE – MVVM

MVVM, short for Model-View-ViewModel, is an architectural pattern based on front-end development.

Model: refers to the data in the data property of the vue object. The data here is going to be displayed on the page.

View: Refers to the HTML page in vUE where the data is to be displayed. In VUE, this is also called the “View template”.

ViewModel: refers to the VM object in vue.js when we write the code. It is the core of vue.js and is responsible for connecting the View and Model to ensure the consistency of the View and data, so in the previous code, the data in data is displayed in the P tag.

Identify each part in the code

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>
</head>
<body>
<! -- View -->
    <div id="app">
        {{message}}
    </div>

    <script>
        // View Model
        let vm = new Vue({
            el:'#app'.// Model 
            data: {message:'hahah'}});</script>
</body>
</html>
Copy the code

The EL and data properties can be accessed directly from the VM object in the browser at console.log, and even data in data can be accessed

$represents attributes of a VM object, which are assigned when the VM object is initialized

Console. log(vm.$el) // The extent to which vm objects can be controlled console.log(vm.$data); Console. log(vm.$data.message); // Access the data in data console.log(vm.message); // This message is the data declared in data. The variable name shows other data, and message is just an example.Copy the code

The template syntax displays the data

  • Text interpolation:{{}}The or instructionv-text

To display plain text data in double tags, the {{}} or instruction v-text is used to complete the data display, and js expressions and code conforming to JS syntax can be supported in double brackets

<p id="app">
    {{message}}
    <span v-text="message"></span>    	
	<span v-once>{{ message }}</span>
</p>
<! Whenever the MSG variable changes on the bound data object, the contents of the interpolation are updated. If the v-once instruction is used, the data is interpolated only once, and the interpolated content is not updated when the data changes -->
Copy the code
{{number + 1}} {{ok? 'YES' : 'NO'}} {{message.split('').reverse().join('')}} <div v-bind:id=" list-' + id"></div> <div v-bind:id=" list-' + id"> <! {{var a = 1}} <! -> {{if (ok) {return message}}Copy the code
  • To display data in the form input box, add the V-Model attribute to complete the display of data
<span id="app">
    <input type="text" v-model="message">
    <textarea name="" id="" cols="30" rows="10" v-model="message"></textarea>
</span>
<! If the user changes the value of the form element, the value of the corresponding data in the data will also change. Even if the page uses the data, the value will change. -->
Copy the code
  • Use the V-HTML attribute if the content of the double tag is to display data that contains HTML code
<body>
<span id="app">
    <span v-html="message"></span>
</span>

<script>
    let vm = new Vue({
        el:'#app'.data: {message:'<h1>msg</h1>'}})</script>
</body>
Copy the code

instruction

Instruction is introduced

Directives are special Directives that have a V – prefix. Each instruction has a fixed role in VUE.

In VUE, many instructions are provided, the common ones are: V-if, V-Model, V-for, and so on.

Directives change the contents or attributes of the element they control when the data in the DATA attribute of the VM object changes.

Because of the historical version of vue, there are two ways to write some instructions:

Written vue1. X written vue2. X -- -- -- -- - > v v - HTML HTML {{plain text}} {{plain text}} v - bind: attribute name -- -- -- -- > : attribute v - on: the event name -- -- -- -- > @ event nameCopy the code

Binding instruction

Vue1. X Written vue2. X
V – bind: attribute names Attribute name:

V-bind dynamically binds the attribute value of the tag to the data variable in the vUE object, implementing operations on the attribute, style, and class of the tag in the VUE object

Attribute operation

Dynamically rendering the value from the vue object’s data property to the tag’s property value tells the property name that your value is a variable from the Vue object and not a string

<div id="app">
    <! -- vuE1.x -->
    <a v-bind:href="url">baidu</a>
    <! -- vue2.x -->
    <a :href="url">baidu</a>
</div>

<script>
    let vm = new Vue({
        el:'#app'.data: {url:'http://www.baidu.com',}})</script>
Copy the code

Class action

The value of the class can be a string/object/object name/array

<div id="app">
<! -- : tells the property name that your value is the corresponding value of the variable from the vue object -->

    <p :class="cls1">Class is a string</p>

    <p :class="{cls1:false}">If the value of the class is an object and the value of the object is false, the clS1 style does not apply</p>
    <p :class="cls3">The value of the class is the object name</p>
    <p :class="[cls1,cls2]">The value of class is an array, and the styles in the array are in effect simultaneously, adding multiple class style classes to the elements in batches</p>
</div>
<script>
    let vm = new Vue({
        el:'#app'.data: {cls1:'box1'.cls2:'box2'.cls3: {'box1':false.'box2':true}}})</script>
Copy the code

Style operations

The value of the style can be a string/object/object name/array

<div id="box">
    <div style="color: red; background: blue">Style1, normal style writing</div>
    <div :style="{color:fc,backgroundColor:'blue'}">Vue changes inline styles where the value is an object</div>
    <div :style="sty">Vue changes the inline style. The value is the object name</div>
    <div :style="[sty,sty1]">Vue modifs the inline style where the value is an array</div>
</div>

<script>
    var vm = new Vue({
        el:'#box'.data: {fc:'red'.ac:'blue'.sty: {color:'yellow'.backgroundColor:'black'},
            sty1: {fontSize:'50px'.border:'5px solid blue'}}})</script>
Copy the code

Conditional orders

Introduction to Conditional Instruction

The condition directive is used to control the display and hiding of elements (the condition is true display, the condition is false do not display), that is, used for conditional rendering of a piece of content

v-if & v-else-if & v-else

Multiple V-else-if statements can occur, but the V-else-if must be preceded by a V-if. It can be followed by a V-else or not.

The V-else instruction represents the v-if “else block.” The V-else element must immediately follow an element with a V-if or V-else-if, otherwise it will not be recognized.


    <div id="app">
        <p v-if="num==0">{{num}}</p>
        <p v-else-if="num==1">one</p>
        <p v-else>else</p>
        
    </div>


    <script>
        let vm = new Vue({
            el:'#app'.data: {num:1}})</script>
Copy the code

v-show

<p v-show="num==1">v-show{{num}}</p>
Copy the code

Similarities and differences between V-if and V-show

It is used in much the same way as v-if, with two differences:

  1. V-show cannot be followed by v-else or V-else-if
  2. V-show hides elements using display: None, while V-if removes elements directly from the HTML document.
Tag elements:<h1 v-show="ok">Hello!</h1>Data: data:{ok:false // true = show, false = hide}Copy the code

Cycle instruction

In VUE, a set of data, either an array or an object, can be rendered to a page using the V-for instruction

  • Circular array
<div id="goods">
    <table border="3">
        <tr>
            <td>The serial number</td>
            <td>id</td>
            <td>name</td>
            <td>price</td>

        </tr>
<! The first element is the data, the second element is the index subscript -->
        <tr v-for="goods,index in book_list">
            <td>{{index}}</td>
            <td>{{goods.id}}</td>
            <td>{{goods.title}}</td>
            <td>{{goods.price}}</td>

        </tr>
    </table>
</div>

<script>
    var vm = new Vue({
        el:'#goods'.data: {book_list:[
            {"id":1."title":"Book Name 1"."price":200},
            {"id":2."title":"Book Name 2"."price":200},
            {"id":3."title":"Book Name 3"."price":200},
            {"id":4."title":"Book Name 4"."price":200},]}})</script>
Copy the code
  • Circular object
	
<ul>
    <! The first element is the value, the second element is the key -->
    <li v-for="value, attr in book">{{attr}}:{{value}}</li>
</ul>
Copy the code
  • Summary: When looping values, the way to not display the index or key of an array is to loop only one variable
<li v-for="book in book_list">{{book.title}}</li>
<li v-for="value in book">{{value}}</li>
Copy the code

Event binding directive

Event Instruction Introduction

Vue1. X version Vue2. X version
V-on: indicates the event name @ Event name

All event names in vUE are js event names

Events in js Event name in vUE
onsubmit @submit
onfocus @focus
onblur @blur
onclick @click

Simple event

Simple event handling logic is simply written in the string

<div id="app">
    <! Add and subtract data in the input box -->
    <button @click="num++">+</button>
    <input type="text" v-model="num">
    <button @click="num--">-</button>
</div>

<script>
    let vm = new Vue({
        el:'#app'.data: {num:0}})</script>
Copy the code

Complex event

The logic for handling complex events is written in a separate function that is placed in the Methods of the vue object and executed by calling the function name

<div id="app">
    <button @click="myalert">alert</button>
</div>

<script>
    let vm = new Vue({
        el:'#app'.data: {num:0.name:'hello'
        },
        methods: {myalert(){
                alert(this.name + '! ')}}})</script>
Copy the code

Vue Object attribute function

The filter

Custom filters are used for some common text formatting. Filters can be used in two places: double curly brace interpolation and after binding directives

Global filter

  • Syntax format
Vue.filter(' name of filter ','fucntion(args){return args. Methods} ')Copy the code
  • Code case – print the price attribute in vue object data to the front page with two decimal digits
<div id="app">
    {{price}}
    {{price|foo}}
</div>

<script>
<! -- toFixed() is the method that js provides to keep the decimal point -->Vue.filter('foo',function(price){return price.toFixed(2)}); Let vm = new Vue({el:'#app', data:{price:2.31456}})</script>
Copy the code
  • Summary of Global Filters
Global filter: syntax format vue.filter (' name of filter ', 'function(args){return args. Method}} ') will be a certain data in the data as the parameters of the filter, to the filter function, and then return the filter after processing the results of the processed results can be achieved by template syntax, output filter template syntax + syntax format {{need to deal with data | filter function name}}Copy the code

Local filter

  • Syntax format
Filters :{function name (args){return args. Methods}}Copy the code
  • Code case
<div id="app">
    {{price}}
    {{price|format}}
</div>

<script>
    var vm = new Vue({
        el:'#app'.data: {price:8.1536
        },
        // Local filter
        filters: {format(money){
                return money.toFixed(2) +'元'}}})</script>
Copy the code
  • Local Filter summary
Local filters only affect data in the current VUE object. Local filters are functions defined in the filters properties of the current VUE objectCopy the code

The evaluated property of the vue object

Calculate properties: this is equivalent to creating a new variable to hold the results of the data calculation


<div id="app">
    <input type="text" v-model="num">+
    <input type="text" v-model="num1">=
    <span>{{mySum}}</span>
</div>

<script>
    let vm = new Vue({
        el:'#app'.data: {num:0.num1:1
        },
        computed: {// mySum receives the result
            mySum(){
                // this refers to the vue object
                return parseFloat(this.num)+parseFloat(this.num1)
            }
        }
    })
</script>
Copy the code

The listening property of the vue object

The listen property helps us listen for changes in data so that we can customize accordingly.

Listen properties is an object, its key is to listen the object or variable, the value is generally a function, when listening for data data changes, will automatically execute the corresponding function, this function when the called, requires two parameters, the first is the changes before the data values, the second is the change after the data values.

<div id="app">
    <input type="text" v-model="num">
    <button @click="num++" >+</button>
</div>
<script>
    let vm = new Vue({
        el:'#app'.data: {num:0
        },
        watch: {Num (v1,v2){}
            num:function (v1,v2) {
                if(this.num>=5) {this.num=5}
                console.log(v1,v2)
            }
        }
    })
</script>
Copy the code

Vue Specifies the life cycle of the object

Each Vue instance goes through a series of initialization procedures when it is created — for example, it needs to set up the data listener, compile the template, mount the instance to the DOM, and update the DOM when the data changes. It also runs functions called lifecycle hooks, which give users the opportunity to add their own code at different stages

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.min.js"></script>
    <script>
    window.onload = function(){
        var vm = new Vue({
            el:"#app".data: {num:0
            },
            beforeCreate:function(){
                console.log("BeforeCreate, VM object not yet created,num="+ this.num);  //undefined
                this.name=10; // There is no this object, so the name set is invalid and is overwritten by 0 when the object is created
            },
            created:function(){
                console.log("Created, the VM object has been created, the range of elements to control has been set,num="+this.num );  / / 0
                this.num = 20;
            },
            beforeMount:function(){
                console.log( this.$el.innerHTML ); // <p>{{num}}</p>
                console.log("BeforeMount, the VM object does not display data to the page,num="+this.num ); / / 20
                this.num = 30;
            },
            mounted:function(){
                console.log( this.$el.innerHTML ); // <p>30</p>
                console.log("Mounted,vm object (num= 0)"+this.num); / / 30
            },
            beforeUpdate:function(){
                // this.$el refers to the element #app currently controlled by vue.js
                console.log( this.$el.innerHTML );  // <p>30</p>
                console.log("BeforeUpdate, the VM object does not display the updated data on the page,num="+this.num); // beforeUpdate----31
                
            },
            updated:function(){
                console.log( this.$el.innerHTML ); // <p>31</p>
                console.log("Num =" + this.num ); // updated----31}}); }</script>
</head>
<body>
    <div id="app">
        <p>{{num}}</p>
        <button @click="num++">button</button>
    </div>
</body>
</html>
Copy the code
  • conclusion
When vue is in use, if you want to initialize an operation, place the code that initializes the operation in Mounted. The Mounted stage is when you modify the data on the page, after the VM object has implemented the data on the page. General page initialization use. For example, an Ajax request is made after the user visits the page and loads successfully. The other one is created, and this is the stage where after the vue object is created, you put the ajax code that asks for the backend data into the Created and before the page loads, you make an HTTP request to the backend to get the data, and you write that code in the createdCopy the code

Prevents events from bubbling and page refreshing

Event bubble: when an event of a js neutron element is triggered, it causes similar events of the parent element to be triggered simultaneously.

Event bubbling has both advantages and disadvantages.

Benefit: If this phenomenon is used correctly, event delegates can be implemented, improving the performance of special effects

Cons: If not used correctly, it can lead to unnecessary bugs.

  • @click.stop to stop event bubbling
  • @click.prevent to prevent form submission
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box1{
            width: 200px;
            height: 200px;
            background: #ccc;
        }
        .box2{
            width: 100px;
            height: 100px;
            background: pink;
        }
    </style>
    <script src="vue.js"></script>
    <script>
    window.onload = function(){
        var vm = new Vue({
            el:"#app".data: {}})}</script>
</head>
<body>
    <div id="app">
        <div class="box1" @click="alert('box1')">
            <div class="box2" @click.stop.prevent="alert('box2')"></div>   <! -- @click.stop to prevent events from bubbling -->
        </div>

        <form action="#">
            <input type="text">
            <input type="submit">
            <input type="submit" value="Submit 02" @click.prevent=""> <! -- @click.prevent to prevent form submission -->
        </form>
    </div>

</body>
</html>
Copy the code

Comprehensive case — TODOLIST

  • The source HTML code
<! DOCTYPEhtml>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>todolist</title>
	<style type="text/css">
		.list_con{
			width:600px;
			margin:50px auto 0;
		}
		.inputtxt{
			width:550px;
			height:30px;
			border:1px solid #ccc;
			padding:0px;
			text-indent:10px;
		}
		.inputbtn{
			width:40px;
			height:32px;
			padding:0px;
			border:1px solid #ccc;
		}
		.list{
			margin:0;
			padding:0;
			list-style:none;
			margin-top:20px;
		}
		.list li{
			height:40px;
			line-height:40px;
			border-bottom:1px solid #ccc;
		}

		.list li span{
			float:left;
		}

		.list li a{
			float:right;
			text-decoration:none;
			margin:0 10px;
		}
	</style>
</head>
<body>
	<div class="list_con">
		<h2>To do list</h2>
		<input type="text" name="" id="txt1" class="inputtxt">
		<input type="button" name="" value="Add" id="btn1" class="inputbtn">

		<ul id="list" class="list">
			<! -- javascript:; # block a tag from jumping -->
			<li>
				<span>Learning HTML</span>
				<a href="javascript:;" class="up"></a>
				<a href="javascript:;" class="down"></a>
				<a href="javascript:;" class="del">delete</a>
			</li>
			<li><span>Learning CSS</span><a href="javascript:;" class="up"></a><a href="javascript:;" class="down"></a><a href="javascript:;" class="del">delete</a></li>
			<li><span>Learning javascript</span><a href="javascript:;" class="up"></a><a href="javascript:;" class="down"></a><a href="javascript:;" class="del">delete</a></li>
		</ul>
	</div>
</body>
</html>
Copy the code
  • Implementation code
<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>todolist</title>
   <style type="text/css">
      .list_con{
         width:600px;
         margin:50px auto 0;
      }
      .inputtxt{
         width:550px;
         height:30px;
         border:1px solid #ccc;
         padding:0px;
         text-indent:10px;
      }
      .inputbtn{
         width:40px;
         height:32px;
         padding:0px;
         border:1px solid #ccc;
      }
      .list{
         margin:0;
         padding:0;
         list-style:none;
         margin-top:20px;
      }
      .list li{
         height:40px;
         line-height:40px;
         border-bottom:1px solid #ccc;
      }

      .list li span{
         float:left;
      }

      .list li a{
         float:right;
         text-decoration:none;
         margin:0 10px;
      }
   </style>
    <script src="vue.js"></script>
</head>
<body>
   <div class="list_con" id="app">
      <h2>To do list</h2>
      <input type="text" v-model="content" id="txt1" class="inputtxt">
      <input type="button" @click="add" value="Add" id="btn1" class="inputbtn">

      <ul id="list" class="list">
         <! -- javascript:; # block a tag from jumping -->
         <li v-for="item,index in todolist">
            <span>{{item}}</span>
            <a href="javascript:;" class="up" @click="up(index)"></a>
            <a href="javascript:;" class="down" @click="down(index)"></a>
            <a href="javascript:;" class="del" @click="del(index)">delete</a>
         </li>

      </ul>
   </div>
    <script>
        let vm = new Vue({
            el:'#app'.data: {content:' '.todolist: ['to learn HTML'.'learning CSS'.'learning javascript'.'learning c'],},methods: {add(){
                    // Append an array member to js using push
                    this.todolist.push(this.content);
                    // This will clear the input box
                    this.content=' '
                },
                del(index){
                    // The splice high-order function in js can specify the number of members to delete from the specified subscript, and replace the members at the specified position
                    // splice(delete the starting subscript, delete the number of members, replace the deleted element)
                    this.todolist.splice(index,1);
                },
                up(index){
                    / / up
                    // Splice first removes the moved element and saves it in memory. Then, splice inserts the deleted element into the array. Splice returns a content -- the manipulated data object
                    let currentItem = this.todolist.splice(index,1) [0];
                    this.todolist.splice(index-1.0,currentItem)
                },
                down(index){
                    / / move down
                    // The principle is similar to that of moving up
                    let currentItem = this.todolist.splice(index,1) [0];
                    this.todolist.splice(index+1.0,currentItem)
                }
            }
        })
    </script>
</body>
</html>
Copy the code

conclusion

The article was first published in the wechat public account program Yuan Xiaozhuang, synchronized with nuggets.

Please explain where it came from. If you pass by, please put out your cute little finger and click like before you go (╹▽╹)