A. Introduction of Vue

The characteristics of the 1.1 Vue

  • Adopt componentization pattern, improve code reuse rate, and make code better maintenance

  • Declarative coding, so that coders do not need to directly operate the DOM, improve development efficiency

  • Using virtual DOM+ excellent Diff algorithm, try to reuse DOM nodes

    ​ 

1.2 Set up the Vue development environment

You can go to the website link to see the installation steps:Vue official website address

We’ll just use script

  • CDN
The full version (contains the complete warning and debug mode) : < script SRC = "https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js" > < / script > compression (delete the warning) : < script SRC = "https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.min.js" > < / script >Copy the code
  • It is best to use download Vue Devtools

2. Vue core

2.1 I met Vue

  • For Vue to work, you must create an instance of Vue and pass in a configuration object

  • The code in the root container is still HTML compliant, but with some special Vue syntax mixed in

  • The code in the root container is called a Vue template

  • In real development there is only one instance of Vue and it is used with components;

  • XXX in {XXX}} can be automatically read to the corresponding attributes in data, and XXX is automatically executed when writing js expressions;

  • . For example: {{name toUpperCase ()}} capital, {{1 + 1}} the output value is 2, {{Date. Now ()}} get timestamp

  • Once the data in the data changes, the page where the data is used is automatically updated;

Note the distinction between js expressions and JS code (statements)1.Expression: An expression produces a value, which can be placed wherever the value is needed:1). a
(2). a+b
(3). demo(1)
(4). x === y ? 'a' : 'b'

2.Js code (statement) (1). if() {} (2). for() {}Copy the code
  • The Vue instance and the template are one to one. In the following two sections of code, neither of them can be parsed properly
<div class="root">
        <h1>hello,{{name}}</h1>
</div>

<div class="root">
    <h1>hello,{{name}}</h1>
</div>

<script>
    new Vue({
        el: '.root',
        data: { 
            name:'cez'
        },
        methods: {}
    });
</script>
Copy the code
<div id="root"> <h1>hello,{{name}},{{address}}</h1> </div> <script> new Vue({ el: '#root', data: {name: 'cez}, the methods: {}}) new Vue ({el:' # root, data: {address: 'shandong'}, the methods: {}}); </script>Copy the code

Full version code:

<! DOCTYPE html><html>
<head>
	<meta charset="UTF-8" />
	<title>I met the Vue</title>
	<! -- Introduce Vue -->
	<script type="text/javascript" src=".. /js/vue.js"></script>
</head>
<body>
	<! -- Get a container ready -->
	<div id="demo">
		<h1>Hello, {{name. ToUpperCase ()}}, {{address}}, {{1 + 1}}, {{Date. Now ()}}</h1>
	</div>

	<script type="text/javascript">
		Vue.config.productionTip = false // Prevent vue from generating a production prompt at startup.

		// Create a Vue instance
		new Vue({
			el: '#demo'.//el is used to specify which container the current instance of Vue is serving. The value is usually a CSS selector string. \
			/ / el: document getElementById (" root "), also can write, but is not recommended
			data: { // Data is used to store data, which is used by the container specified by el. For the time being, the value is written as an object.
				name: 'zgc'.address: 'Beijing'}})</script>
</body>
</html>
Copy the code

2.2 Template Syntax

  • There are two broad categories of Vue template syntax:

    • Interpolation syntax:

      • Function: Used to parse tag body content
      • Write: {{XXX}}, XXX is a JS expression, and can directly read all attributes in data
    • Instruction syntax:

      • Function: Used to parse tags (including: tag attributes, tag body content, binding events…)

      • For example, v-bind:href=” XXX “or omit v-bind. XXX also writes js expressions and can directly read all attributes in data. There are many instructions in Vue, and the form is v-???? For example, v-bind

<! DOCTYPE html><html>
<head>
	<meta charset="UTF-8" />
	<title>Template syntax</title>
	<! -- Introduce Vue -->
	<script type="text/javascript" src=".. /js/vue.js"></script>
</head>
<body>
	
	<! -- Get a container ready -->
	<div id="root">
		<h1>The interpolation of grammar</h1>
		<h3>Hello, {{name}}</h3>
		<hr />
		<h1>Command syntax</h1>
		<a v-bind:href="school.url.toUpperCase()" x="hello">Click I go to {{school.name}} learn 1</a>
		<a :href="school.url" v-bind:x="hello">Click me to {{school.name}} learn 2</a>
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false // Prevent vue from generating a production prompt at startup.

	new Vue({
		el: '#root'.data: {
			name: 'zgc'.school: {
				name: 'tsinghua'.url: 'http://www.atguigu.com',},hello: 'hello'}})</script>
</html>
Copy the code

2.3 Data Binding

Vue has two data binding methods:

  • V-bind: Data can only flow from data to the page.
  • Two-way binding (V-Model) : Data can flow not only from data to page, but also from page to data.

Remark:

  • Bidirectional binding is generally applied to form class elements (such as input, select, etc.)
  • V-model: Value can be shortened to V-Model because v-Model collects value by default.
<! DOCTYPE HTML > < HTML > <head> <meta charset="UTF-8" /> <title> Data binding </title> <! <script type="text/javascript" SRC =".. /js/vue.js"></script> </head> <body> <! <div id="root"> <! --> <! <input type="text" v-model:value="name"><br/> --> <! <input type="text" :value="name"><br /> <br /> <! The following code is incorrect because v-Model can only be applied to form class elements (input class elements) --> <! -- <h2 v-model:x="name"> </h2> --> </div> </body> <script type="text/javascript"> vue.config.productionTip = false // Prevent vue from generating a production prompt at startup. New Vue ({el: '# root, data: {name:' it is silicon valley '}}) < / script > < / HTML >Copy the code

2.4 Two ways of writing EL and data:

The data with el2Kind of writing1.El has2Kind of written1). New Vue configures the EL attribute. (2Create a Vue instance, and then run the Vue instance from vm.'#root') specifies the value of EL.2.The data are2Kind of written1). Object (2). How to choose functions: At present, either way can be written, later when learning components, data must use functions, otherwise an error will be reported.3.An important rule: for functions managed by Vue, never write arrow functions. Once you write arrow functions,thisIt's no longer an instance of Vue. Examples of functions managed by Vue: data (), method, etc.thisWill become a WindowCopy the code

El:

The EL attribute, also known as mount point, can be thought of as short for element. To create a VUE instance, you need to know on which element the vUE instance is being created and which view is being operated.

1.Set the EL attribute <div id="app"></div> 
new Vue({ 
  el: "#app".render: h= > h(App) 
}) 
2.Use the $mount interfacenew Vue({
  render: h= > h(App) 
}).$mount("#app");
Copy the code

Data:

The data attribute is also called internal data. The value of this attribute can be an object or a function, but functions are preferred. Functions within objects are also called methods. And if data is in a component, you must use a function.

When creating multiple Vue instances using the same options object, if the data property value is an object, When you create a Vue instance using new Vue(options), you assign the options.data property value directly to the Vue instance. Data property. Since the object is assigned to the copied address, the data property value of multiple instances points to the address of the same object. Multiple instances share a data object, and when one instance changes the data object, the data object of the other instance is also changed.

When the data attribute value is a function, Vue executes the data() function when creating an instance, and assigns the object returned as a result of the function execution to Vue instance. One change does not affect the other, they are independent.

1.Using the objectdata: {n: 0 }

2.Using the functiondata(){ return{ n: 0}}Copy the code

2.5 MVVM

  • MVVM: Model-view-ViewModel is a software architecture pattern

    • M: Model corresponds to data in data
    • V: View template
    • VM: ViewModel Vue instance object
  • All of the attributes in data end up on the VM

  • {{$options}} {{$emit}} = {$emit}} = {$emit}} = {$emit}} = {$emit}} = {$emit}} = {$emit}}

2.6 Object. DefineProperty ()

Vue data hijacking and data brokers, computing properties, etc., all use this method and must be understood. If you can see how this method works in an instant, take a look at my code below to recall and learn more. If not, take a look at my other blog.

<! DOCTYPE html><html>

<head>
	<meta charset="UTF-8" />
	<title>Review the object.defineProperty method</title>
</head>

<body>

	<script type="text/javascript">
		let number = 18
		let person = {
			name: 'Joe'.sex: 'male',}// object.defineProperty Adds attributes to an Object
		Object.defineProperty(person, 'age', {
			// There are three parameters (object, property name, options configuration object {})
			// value: 18,
			Enumerable: true, // controls whether the property can be enumerated (traversal). The default value is false
			// writable:true, // controls whether the property can be modified. The default value is false
			// Signals :true // Controls whether the properties can be removed, without additional information. The default value is false

			// The get function is called when someone reads the age property of person, and the return value is the age value
			get() {
				console.log('Someone has read the age property')
				return number
			},

			// When someone changes the age property of person, the set function is called and receives the changed value
			set(value) {
				console.log('Someone changed the age attribute and the value is', value)
				number = value
			}

		})

		// console.log(Object.keys(person))

		console.log(person)
	</script>
</body>

</html>
Copy the code

2.7 Data Broker

What is a data Broker

<! DOCTYPE html><html>
	<head>
		<meta charset="UTF-8" />
		<title>What is a data Broker</title>
	</head>
	<body>
		<! -- Data broker: operation (read/write) on properties of another object through an object broker -->
		<script type="text/javascript" >
			let obj = {x:100}
			let obj2 = {y:200}

			Object.defineProperty(obj2,'x', {get(){
					return obj.x
				},
				set(value){
					obj.x = value
				}
			})
		</script>
	</body>
</html>
Copy the code

Properties in obj objects can be manipulated using obj2 objects

Vue data agent

1. Data proxy in Vue: Using VM objects to proxy operations (read/write) on properties in data objects

2. Benefits of data agent in Vue: more convenient operation of data in data

3. Basic principle: Use object.defineProperty () to add all attributes in a data Object to the VM. Specify a getter/setter for each property added to the VM. To manipulate (read/write) the corresponding property in the data inside the getter/setter.

<! DOCTYPE html><html>
<head>
	<meta charset="UTF-8" />
	<title>Data broker in Vue</title>
	<! -- Introduce Vue -->
	<script type="text/javascript" src=".. /js/vue.js"></script>
</head>
<body>

	<! -- Get a container ready -->
	<div id="root">
		<h2>School name: {{name}}</h2>
		<h2>School address: {{address}}</h2>
		<! If you do not have a data broker, you will need to find the name and address attributes in _data. This is too much work, because the VM does not have these two attributes. {{_data while forming. The name}} < / h2 > < h2 > school address: {{_data while forming. Address}} < / h2 > -- >
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false // Prevent vue from generating a production prompt at startup.

	const vm = new Vue({
		el: '#root'.data: {
			name: 'Still Silicon Valley'.address: 'Hongfu Science Park'}})</script>

</html>
Copy the code

The name of the school on the page was originally shangsilicon Valley, and the content of the page changed with the change of data

2.8 Event Handling

Basic use of events

The basic uses of events are as follows: 1. Use v-ON: XXX or @xxx to bind an event, where XXX is the event name. 2. Event callbacks need to be configured in the Methods object and will eventually be configured on the VM; 3. Do not use arrow functions for functions configured in methods. Otherwise this is not a VM; This refers to a VM or component instance object; this refers to a vm or component instance object. 5.@click=”demo” and @click=”demo($event)”

The exact modifier allows you to control the events triggered by the exact combination of system modifiers.

<! -- Trigger even when Alt or Shift are pressed together --><button @click.ctrl="onClick">A</button><! -- Triggers only when Ctrl is pressed --><button @click.ctrl.exact="onCtrlClick">A</button><! -- Triggered when no system modifier has been pressed --><button @click.exact="onClick">A</button>
Copy the code

Mouse button modifiers These modifiers restrict the handler to responding only to a particular mouse button.

.left
.right
.middle
Copy the code
<! DOCTYPE html><html>
	<head>
		<meta charset="UTF-8" />
		<title>Basic use of events</title>
		<! -- Introduce Vue -->
		<script type="text/javascript" src=".. /js/vue.js"></script>
	</head>
	<body>
		<! -- Get a container ready -->
		<div id="root">
			<h2>Welcome to {{name}}</h2>
			<! -- <button v-on:click="showInfo">
			<button @click="showInfo1">Click "I prompt message 1" (no arguments)</button>
                        <button @click.right="showInfo1">Right click on my prompt 1 (no arguments)</button>
			<button @click="showInfo2($event,66)">Click my Prompt message 2 (pass parameter)</button>
                      
                         <! -- Triggers only when CTRL is pressed -->
                       <button v-on:click.ctrl.exact="showInfo1">A</button>
                        
                        <! -- Shift triggers even when pressed with Alt or CTRL -->
		        <button v-on:click.shift="showInfo1">A</button>
                       
                        <! -- Triggered when no system modifier has been pressed -->
		        <button v-on:click.exact="showInfo1">A</button>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false // Prevent vue from generating a production prompt at startup.

		const vm = new Vue({
			el:'#root'.data: {name:'Still Silicon Valley',},methods: {showInfo1(event){
					// console.log(event.target.innerText)
					// console.log(this) // Where this is vm
					alert('Hello! ')},showInfo2(event,number){
					console.log(event,number)
					// console.log(event.target.innerText)
					// console.log(this) // Where this is vm
					alert('Hello classmate!! ')}}})</script>
</html>
Copy the code

Event modifier

Event modifiers in Vue: 1. Prevent: prevents default events (commonly used); 2. Stop: Prevents the event bubble (common). 3. Once: The event is triggered only once (commonly used). 4. Capture: Use the capture mode of events; 5. Self: Fires an event only if the event. Target is an element of the current operation; 6. Passive: The default action is to execute the event immediately without waiting for the event callback to complete.

<! DOCTYPE html><html>
<head>
	<meta charset="UTF-8" />
	<title>Event modifier</title>
	<! -- Introduce Vue -->
	<script type="text/javascript" src=".. /js/vue.js"></script>
	<style>
		* {
			margin-top: 20px;
		}

		.demo1 {
			height: 50px;
			background-color: skyblue;
		}

		.box1 {
			padding: 5px;
			background-color: skyblue;
		}

		.box2 {
			padding: 5px;
			background-color: orange;
		}

		.list {
			width: 200px;
			height: 200px;
			background-color: peru;
			overflow: auto;
		}

		li {
			height: 100px;
		}
	</style>
</head>

<body>
	<! -- Get a container ready -->
	<div id="root">
		<h2>Welcome to {{name}}</h2>
		<! -- Block default events (common) -->
		<a href="http://www.atguigu.com" @click.prevent="showInfo">Click on my info</a>

		<! -- Stop event bubbling -->
		<div class="demo1" @click="showInfo">
			<button @click.stop="showInfo">Click on my info</button>
			<! All ancestor bubbles outside the layer on which the block event bubble is added will be blocked -->
			<! The -- modifier can be written consecutively -->
			<! <a href="http://www.atguigu.com" @click.prevent. Stop ="showInfo"> </a> -->
		</div>

		<! -- Event triggers only once -->
		<button @click.once="showInfo">Click on my info</button>

		<! -- Use event capture mode -->
		<div class="box1" @click.capture="showMsg(1)">
			div1
			<div class="box2" @click="showMsg(2)">
				div2
			</div>
		</div>

		<! -- Event is fired only if event.target is an element of the current operation; -->
		<div class="demo1" @click.self="showInfo">
			<button @click="showInfo">Click on my info</button>
		</div>

		<! -- The default behavior of the event executes immediately, without waiting for the event callback to complete; -->
		<ul @wheel.passive="demo" class="list">
			<li>1</li>
			<li>2</li>
			<li>3</li>
			<li>4</li>
		</ul>
		<! -- @wheel @scroll -->
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false // Prevent vue from generating a production prompt at startup.

	new Vue({
		el: '#root'.data: {
			name: 'Still Silicon Valley'
		},
		methods: {
			showInfo(e) {
				// e.topPropagation ()// To stop bubbles
				// e.preventDefault()// Block the default event
				// You can use event modifiers instead of either method
				alert('Hello! ')
				console.log(e.target)
			},
			showMsg(msg) {
				console.log(msg)
			},
			demo() {
				for (let i = 0; i < 100000; i++) {
					console.log(The '#')}console.log('Worn out')}}})</script>

</html>
Copy the code

Keyboard events

1. Common key aliases in Vue: Enter => Enter Delete => DELETE (capture “Delete” and “backspace” keys) Exit => ESC Space => space Newline => TAB (special, Up => UP => Down => Down left => left right => right

2.Vue does not provide alias keys, can use the original key value of the key to unbind, but note to convert to kebab-case (short line name)

3. System modifier keys (special usage) : TAB, CTRL, Alt, Shift, Meta (1). Used with keyup: The event is triggered when the modifier key is pressed and another key is pressed, and then the other key is released. (2). Used with keyDown: Normally triggers events.

4. You can also use keyCode to specify specific keys (not recommended)

<input type="text" placeholder="Press Enter to prompt input." @keydown13.="showInfo">
Copy the code

Vue.config.keycodes. Custom key name = key code, you can customize the key alias

<! DOCTYPE HTML > < HTML > <head> <meta charset="UTF-8" /> <title> Keyboard event </title> <! <script type="text/javascript" SRC =".. /js/vue.js"></script> </head> <body> <! </h2> <input type="text" placeholder=" placeholder "style =" paddING-top: 0px; padding-bottom: 0px; padding-top: 0px; @keydown.huiche="showInfo"> <! -- <input type="text" placeholder=" @keydown.enter="showInfo"> --> <! <input type="text" placeholder=" @keyup.ctrl.y="showInfo"> --> </div> </body> <script Type ="text/javascript"> vue.config. productionTip = false // prevents Vue from generating production prompts at startup. Vue. Config. KeyCodes. Huiche = 13 / / defines a new alias keys Vue ({el: '# root, data: {name:' it is silicon valley '}, the methods: { showInfo(e) { // console.log(e.key,e.keyCode) // if (e.keyCode ! }},}) </script> </ HTML >Copy the code

To be continued

Click to jump :Vue Study Notes (2)