Rampage against vue (Part 4): v-model, summary of the command system, implementation of the carousel example of the command system, example of the marquee effect of the command system, the way to use styles in vue

 

1. v-model

v-modelInstructions on the form <input>, <textarea>and <select>create two-way data binding on the element. It will automatically select the correct method to update the element based on the control type.

Although somewhat magical, it v-modelis essentially syntactic sugar. It is responsible for listening to user input events to update data, and to perform some special processing for some extreme scenarios.

v-modelInternally, use different attributes for different input elements and throw different events:

  • text and textarea elements using the valueproperties and inputevents;

  • checkbox and radio use checkedproperties and changeevents;

  • select field valueas a prop and changeas an event.

 

The core of vue: two-way binding of declarative instructions and data.

What is two-way data binding? In addition, everyone must know the design pattern of vue: MVVM

M is short for Model, V is short for View, and VM is ViewModel.

What is the difference between one-way binding and two-way binding?

One-way binding is very simple, that is, binding the Model to the View. When we update the Model with JavaScript code, the View will automatically update.

With one-way binding, there is two-way binding.

If the user updates the View, the Model data is also automatically updated, in this case, two-way binding.

Under what circumstances can the user update the View? Filling out the form is the most direct example. When the user fills in the form, the state of the View is updated. If the MVVM framework can automatically update the state of the Model at this time, it is equivalent to bidirectionally binding the Model and the View.

In fact, a single item of data also means two-way binding, but the data changes will not be automatically updated after the page changes.

Think of it this way: two-way data binding = one-way data binding + UI event monitoring.

First look at an example of two-way data binding in vue:

<body>
  <div id="app">
    <input type="text" v-model="msg">
    <p>{{msg}}</p>
  </div>
​
​
​
  <script src="./lib/vue.js"></script>
  <script>
    var app = new Vue({
      el:'#app',
      data :{
        msg:''
      }
      
    })
  </script>
</body>

  

 

The page effect is as follows

 

 

The effect shows that when we enter content in the input input box, the following p tag displays the content synchronously . This is the most typical example of two-way data binding. vue uses v-model to implement this idea.

 

Analysis of understanding the realization process of v-model

<body> 
    <div id = "app"> 
        <!-The v-model instruction is easy to understand, in fact, it is a syntactic sugar (sweet) It is the realization of oninput event and binding value-> 
        <input = type "text": value = 'text' @input = 'a valueChange'> 
        <H3> {{text}} </ H3> 
    </ div> 
    <Script type = "text / JavaScript" the src = "./ the node_modules /vue/dist/vue.js "> </ Script> 
    <Script type =" text / JavaScript "> 
        new new Vue ({ 
            EL:" App # ", 
            Template:` `, 
            Data () { 
                return { 
                    text: ' hello ' 
                } 
            },
            methods:{
                    console.log(event.target.value);
        
                valueChange(event){
                    this.text = event.target.value  
                }
            }
        });
    </script>
    
</body>

  

 

Analysis: The v-mode command is a combination of v-bind: vlaue and v-on: input. For the input tag, use v-bind to bind the value attribute, so that the input tag receives the data drive of the data in real time. The h3 tag directly uses the template interpolation method and is directly driven by the data. This is the model for the view

One-way binding.

Bind valuechange and value change events to the input tag. When the input value changes, the valueChange function processes the value of this.text. This is the unidirectional binding of the view to the model. This constitutes a two-way binding.

Simple calculator with v-model

<body>
  <div id="app">
    <input type="text"  v-model='num1'>
    <select v-model='opt'>
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">*</option>
        <option value="/">/</option>
    </select>
​
    <input type="text"  v-model='num2'>
    <button value='=' @click='calc'>=</button>
    <input type="text"  v-model='res'>
​
  </div>
​
  <script src="./lib/vue.js"></script>
  <script>
    var app = new Vue({
      el:'#app',
      data :{
        num1:0,
        num2:0,
        res:0,
        opt:'+'
      },
      methods: {
​
            calc(){
​
                var calcStr = 'parseInt(this.num1)'+ this.opt + 'parseInt(this.num2)';
                this.res = eval(calcStr);
            }
            }
      
    })
  </script>
</body>

  


 

 

Second, the command system summary

 

1. Pay attention to the abbreviations of v-bind and v-on

  The simple way to write v-bind can be used directly : instead:

<img :src="imgSrc" :title="time">    <==对应==>   
<img v-bind:src="imgSrc" v-bind:title="time">

  

  The simple way to write v-on can be replaced directly with @ :

<button @click = "clickHandler">切换</button>  <==对应==>  
<button v-on:click="clickHandler">切换</button>

  

 

2. Assignment to the dom of the page

  v-test, v-html, {{}} are all assigned to the dom of the page, which is equivalent to innerText and innerHTML in js.

 

3. Conditional rendering of the dom of the page

(1) The internal process of v-if

v-if = 'true':    
<!--创建-->   
var oP = document.createElement('p');  
oDiv.appendChild(op);
v-if= 'false':   
<!--销毁-->   
oDiv.removeChild(op);`

  

(2) The internal process of v-show

v-show = 'true':  
oDiv.style.display = 'block';
​
v-show = 'false':   
oDiv.style.display = 'none'

  

(3) Intrinsic process of v-bind

v-bind:class:
oDiv.className += ' active'
 

  

4. The difference between v-if and v-show

  Differences in implementation: v-if is to directly delete or rebuild element nodes from the Dom tree according to the true and false values ​​of the following data; v-show is only modifying the css style of the element, that is, the display attribute value, the element is always in the Dom tree on.

  Compilation process difference: v-if switching has a partial compilation / uninstallation process. During the switching process, the internal event monitoring and subcomponents are appropriately destroyed and rebuilt; v-show is simply a CSS-based switching.

  Differences in compilation conditions: v-if is lazy. If the initial condition is false, nothing is done. Only when the condition becomes true for the first time will local compilation begin; v-show is under any condition (whether the first condition is True) are compiled and then cached, and DOM elements are always retained.

  Difference in performance consumption: v-if has a higher switching consumption, which is not suitable for frequent switching; v-show has a higher initial rendering consumption, which is suitable for frequent switching.

 

5. The idea of ​​vue

  Vue is a progressive JavaScript framework. Most people think that addition is easier than subtraction.

  The vue framework helps do the subtraction (the hard part). People only need the simple part to implement complex dom operations.

 

 

3. Implementation of the carousel diagram of the command system

1. Simple example of carousel

 

	<style type="text/css">
		ul{
			list-style: none;
			overflow: hidden;
			width: 400px; 
		}
		ul li{
			float: left;
			width: 100px;
			height: 40px;
			line-height: 40px;
			background-color: purple;
			color: #fff;
			text-align: center;
		}
		ul li.active{
			background-color: green;
		}
	</style>
</head>
<body>
	<div id="slider">
		
		<img :src='currentImgSrc' alt="">
		<ul>
			<li v-for = '(item,index) in imgArr' :class="{active:currentIndex==index}" @click='clickHandler(index)'>
				{{ index +1 }}
			</li>
		</ul>
	</div>
	<script src="./lib/vue.js"></script>
	<script type="text/javascript">
		// 数据驱动视图

		var imgArr = [
			{id:1,imgSrc:'./images/1.jpg'},
			{id:2,imgSrc:'./images/2.jpg'},
			{id:3,imgSrc:'./images/3.jpg'},
			{id:4,imgSrc:'./images/4.jpg'}

		];
		new Vue({
			el:'#slider',
			template:``,
			data(){
				return{
					imgArr:imgArr,
					currentIndex:0,
					currentImgSrc:'./images/1.jpg'
				}
			},
			methods:{
				clickHandler(index){
					this.currentIndex = index;
					this.currentImgSrc = this.imgArr[index].imgSrc;
				}
			}
		});
	</script>
	
</body>

  

The page effect is as follows

 

2. Advanced carousel

(1) Add click next

	<style type="text/css">
		ul{
			list-style: none;
			overflow: hidden;
			width: 400px; 
		}
		ul li{
			float: left;
			width: 100px;
			height: 40px;
			line-height: 40px;
			background-color: purple;
			color: #fff;
			text-align: center;
		}
		ul li.active{
			background-color: green;
		}
	</style>
</head>
<body>
	<div id="slider">

			<img :src='currentImgSrc' alt="">
			<ul>
				<li v-for = '(item,index) in imgArr' :class="{active:currentIndex==index}" @click='clickHandler(index)'>
					{{ index +1 }}
				</li>
			</ul>
			<button class="btn" @click='nextImg'>下一张</button>
			

		
	</div>
	<script src="./lib/vue.js"></script>
	<script type="text/javascript">
		// 数据驱动视图

		var imgArr = [
			{id:1,imgSrc:'./images/1.jpg'},
			{id:2,imgSrc:'./images/2.jpg'},
			{id:3,imgSrc:'./images/3.jpg'},
			{id:4,imgSrc:'./images/4.jpg'}

		];
		new Vue({
			el:'#slider',
			template:``,
			data(){
				return{
					imgArr:imgArr,
					currentIndex:0,
					currentImgSrc:'./images/1.jpg'
				}
			},
			methods:{
				clickHandler(index){
					this.currentIndex = index;
					this.currentImgSrc = this.imgArr[index].imgSrc;
				},
				nextImg(){
					if(this.currentIndex==this.imgArr.length-1){
						this.currentIndex = -1;
					}

					this.currentIndex++;
					this.currentImgSrc =  this.imgArr[this.currentIndex].imgSrc;
				}

			}
		});
	</script>
	
</body>

  

Page display effect

(2) Instance life cycle hook

  Each Vue instance undergoes a series of initialization processes when it is created-for example, you need to set up data monitoring, compile templates, mount the instance to the DOM and update the DOM when the data changes. At the same time, some functions called lifecycle hooks will be run in this process , which gives users the opportunity to add their own code at different stages.

  Such hooks may be used to execute code after one instance is created:created

	<style type="text/css">
		ul{
			list-style: none;
			overflow: hidden;
			width: 400px; 
		}
		ul li{
			float: left;
			width: 100px;
			height: 40px;
			line-height: 40px;
			background-color: purple;
			color: #fff;
			text-align: center;
		}
		ul li.active{
			background-color: green;
		}
	</style>
</head>
<body>
	<div id="slider">

			<img :src='currentImgSrc' alt="">
			<ul>
				<li v-for = '(item,index) in imgArr' :class="{active:currentIndex==index}" @click='clickHandler(index)'>
					{{ index +1 }}
				</li>
			</ul>
			<button class="btn" @click='nextImg'>下一张</button>


		
	</div>
	<script src="./lib/vue.js"></script>
	<script type="text/javascript">
		// 数据驱动视图

		var imgArr = [
			{id:1,imgSrc:'./images/1.jpg'},
			{id:2,imgSrc:'./images/2.jpg'},
			{id:3,imgSrc:'./images/3.jpg'},
			{id:4,imgSrc:'./images/4.jpg'}

		];
		new Vue({
			el:'#slider',
			template:``,
			data(){
				return{
					imgArr:imgArr,
					currentIndex:0,
					currentImgSrc:'./images/1.jpg'
				 // Lifecycle method
			created () {
			},
				}
            setInterval (this.nextImg, 2000)   
            // The setInterval () method can call a function or calculation expression according to a specified period (in milliseconds) 
			, 

			methods: { 
				clickHandler (index) { 
					this.currentIndex = index; 
					this.currentImgSrc = this.imgArr [index] .imgSrc; 
				}, 
				nextImg () { 
					if (this.currentIndex == this.imgArr.length-1) { 
						this.currentIndex = -1; 
					} 

					this.currentIndex ++; 
					this.currentImgSrc = this.imgArr [this.currentIndex] .imgSrc; 
				} 

			} 
		}); 
	</ script> 
	
</ body>

  

After setting the created lifecycle method, the images are automatically rotated on the page

There are also other hooks that are called at different stages of the instance life cycle, such as , and . Lifecycle hook context points to call its Vue instance.mountedupdateddestroyedthis

  The created method can also be used to get cookies and sessions.

(3) Stop / start the timer when the mouse moves in / out

 

	<style type="text/css">
		ul{
			list-style: none;
			overflow: hidden;
			width: 400px; 
		}
		ul li{
			float: left;
			width: 100px;
			height: 40px;
			line-height: 40px;
			background-color: purple;
			color: #fff;
			text-align: center;
		}
		ul li.active{
			background-color: green;
		}
	</style>
</head>
<body>
	<div id="slider">

			<img :src='currentImgSrc' alt="" @mouseover='stoptimer' @mouseleave='opentimer'>
			<ul>
				<li v-for = '(item,index) in imgArr' :class="{active:currentIndex==index}" @click='clickHandler(index)'>
					{{ index +1 }}
				</li>
			</ul>
			<button class="btn" @click='nextImg'>下一张</button>


		
	</div>
	<script src="./lib/vue.js"></script>
	<script type="text/javascript">
		// 数据驱动视图

		var imgArr = [
			{id:1,imgSrc:'./images/1.jpg'},
			{id:2,imgSrc:'./images/2.jpg'},
			{id:3,imgSrc:'./images/3.jpg'},
			{id:4,imgSrc:'./images/4.jpg'}

		];
		new Vue({
			el:'#slider',
			template:``,
					currentIndex: 0,
					imgArr: imgArr,
				return {
			data () {
					currentImgSrc: './ images / 1.jpg', 
					timer: null 
				} 
			}, 
			created () { 
				 // life cycle method 
            this.timer = setInterval (this.nextImg, 500)   
            // setInterval () method can follow the specified cycle (In milliseconds) to call a function or calculation expression 
			}, 

			methods: { 
				clickHandler (index) { 
					this.currentIndex = index; 
					this.currentImgSrc = this.imgArr [index] .imgSrc; 
				}, 
				nextImg () { 
					if (this. currentIndex == this.imgArr.length-1) { 
						this.currentIndex = -1; 
					} 

					this.currentIndex ++; 
					this.currentImgSrc = this.imgArr [this.currentIndex] .imgSrc; 
				}, 
				stoptimer () {
					clearInterval (this.timer); // stop timer 
				}, 
				opentimer () { 
					 this.timer = setInterval (this.nextImg, 500)   
					 // start timer 
				} 


			} 
		}); 
	</ script> 
	
</ body>

  

 

Page display effect

 

 

 Note that you cannot directly call this.created lifecycle method when starting the timer, you must start the timer directly.

 

4. The marquee effect of the command system

 

<body> 
  <!-2. Create a zone to be controlled-> 
  <div id = "app"> 
    <input type = "button" value = "wave up" @ click = "lang"> 
    <input type = "button" value = "Low profile" @ click = "stop"> 

    <h4> {{msg}} </ h4> 

  </ div> 

  <script> 
    // Note: In the VM instance, if you want to get the data on Data, or want to call methods in methods, must be accessed through this. Data attribute name or this. Method name, this here means our new VM instance object 
    var vm = new Vue ({ 
      el: ' #app ', 
      data: { 
        msg:' Why development, don't wave ~~! ', 
        intervalId: null // Define timer Id on data 
      }, 
      methods: { 
        lang () { 
          // console.log (this.msg) 
          // Get the first character of the head 
          // this

          if (this.intervalId! = null) return; 

          this.intervalId = setInterval (() => { 
            var start = this.msg.substring (0, 1) 
            // Get all the characters behind 
            var end = this.msg. substring (1) 
            // Re-splice to get a new string and assign it to this.msg 
            this.msg = end + start 
          }, 400) 

          // Note: The VM instance will monitor all data changes in its own data, as long as As soon as the data changes, the latest data will be automatically synchronized from the data to the page; [Benefit: The programmer only needs to care about the data, no need to consider how to re-render the DOM page] 
        }, 
        stop () {// Stop Timer 
          clearInterval (this.intervalId) 
          // Whenever the timer is cleared, you need to reset the intervalId to null 
          this.intervalId = null; 
        } 
      } 
    }) 


    // Analysis:
    // 1. Bind a click event to the [Lang Up] button v-on @ 
    // 2. In the event processing function of the button, write the relevant business logic code: get the msg string, and then call the string substring to perform the string interception operation, extract the first character and put it in the last position; 
    // 3. In order to realize the function of automatic interception by clicking the next button, you need to put the code in step 2 into Go to a timer; 
  </ script> 
</ body>

  

Page display effect

V. Using styles in Vue (added by v-bind)

Use class style

  1. Array

<h1: class = "['red', 'thin']"> This is an evil H1 </ h1>

  

  1. Use ternary expressions in arrays

<h1: class = "['red', 'thin', isactive? 'active': '']"> This is an evil H1 </ h1>

  

  1. Nested objects in an array

<h1: class = "['red', 'thin', {'active': isactive}]"> This is an evil H1 </ h1>

  

  1. Use objects directly

<h1: class = "{red: true, italic: true, active: true, thin: true}"> This is an evil H1 </ h1>

  

Use inline style

  1. Directly on the element :styleform, the object writing style

<h1: style = "{color: 'red', 'font-size': '40px'}"> This is a kind H1 </ h1>

  

  1. The style object that defines the datamiddle, and direct reference to :stylethe

  • Define the style on the data:

data: {
        h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' }
}

  

  • In the element, the style object is applied to the element through the form of attribute binding:

<h1: style = "h1StyleObj"> This is a kind H1 </ h1>

  

  1. In :styleby the array, a plurality of reference datapatterns on objects

  • Define the style on the data:

data: {
        h1StyleObj: { color: 'red', 'font-size': '40px', 'font-weight': '200' },
        h1StyleObj2: { fontStyle: 'italic' }
}

  

  • In the element, the style object is applied to the element through the form of attribute binding:

<h1: style = "[h1StyleObj, h1StyleObj2]"> This is a kind H1 </ h1>

  

 

 

 

 

 

 

 

References

[1] https://www.cnblogs.com/crazymagic/p/9726673.html

[2]https://www.cnblogs.com/yangk1996/p/10844358.html

Guess you like

Origin www.cnblogs.com/Nicholas0707/p/12677061.html