Wang Jianfeng vue notes

Keywords: Javascript Vue.js

vue notes

1, Build an integrated environment for vue

1. CDN static resources are directly introduced into html files

<script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/2.6.14/vue.js"></script>

2. Import the vue.js file you wrote into the project, put it in the project folder, and package it with webpack

import Vue from './vue.js'
new Vue({
    el:"#app",
    data:{
        msg:"wh Hello",
    }
})

3. Build your own scaffolding

The vue.js file is introduced into the project, placed in the project folder, and packaged with webpack

In this process, the configuration file should manually configure the entry, exit, loader, plug-in and development environment

//Entry file
import Vue from 'vue'
import MyCom from './App.vue'
new Vue({
		render(h){return h(MyCom)}		
}).$mount('#app')

4. Use official scaffolding to build

cnpm install @vue/cli -g download official scaffolding

vue create app1 creates a project name. The name should be in English as far as possible, and should not start with a number

Select the tool to be generated by default, regardless of direct enter

Enter the project folder: cd app1 / / enter the project folder, or directly open the terminal in the project folder

Start: the package file generated by npm run serve will not be written to the disk in memory for the development phase
Or the package file generated by npm run build is used in dist to launch the project

5. Visual creation

When the official scaffold is installed, it can be used directly

cnpm install @vue/cli -g a visual interface pops up on the page

2, Basic instruction

1. Basic instruction

1. {{msg}} you can write the msg attribute value in the data object directly in the page
2. v-html is equivalent to innerHTML
3. v-text is equivalent to innerText
4. v-pre plug-in expressions are recognized as text instead of js expressions
5. When v-cloak inserts vue data, the tag with this attribute will be deleted. This can solve the problem of loading the original code without vue data when loading the page. You can set display:none for the v-cloak attribute first, so that the data in loading vue can re render the page

 <div v-html='price'></div>  <!-- The bottom is .innerHTML  stay price The label written inside can be identified  -->
 <div v-text="prices"></div> <!-- The bottom is .innerText  -->
 <div v-pre>{{msg}}</div>  <!-- I won't compile  -->
 <div v-cloak> </div>  insert vue The tag with this attribute will be deleted when the data is loaded. This can solve the problem that the page is loaded first and not added vue Data								The original code can be given first v-cloak Property settings display:none This is loading vue The data is to re render the page
                              

6. Bind attribute v-bind to element
The attributes in all tags are bound to the variables in js:
Standard writing: v-bind:src = ""
Short form:: src = ""

2. Event instruction

v-on: event = "event function" can be called or not

@Is a shorthand for an instruction that binds events

<button v-on:click=fn()>vue click</button>
<button @click=change1()>Change theme</button>

3. Event modifier

. stop prevents bubbling, blocking all bubbling behavior that passes through the current element

. prevent block default events

. capture when you add an event listener, let the event trigger during the capture phase

. self when the events of other elements are triggered, the event chain will pass through it, and its events will not be triggered whether in the capture or bubble stage. Only when it is an accurate object can it trigger events. Although it will not be affected by others, its own event will still generate an event chain when it is triggered. Passing through other elements does not prevent it from continuing to bubble to other elements

The. Once event is triggered only once. After triggering, the event is unbound

Use with multiple modifiers: hyphenation

The direction of this

this is the caller corresponding to the function or method found closest to its nested function or method

3, Style binding

1. Style binding for css

	<style type="text/css">
		    .box{
				width: 200px;
				height: 200px;
			}
			.danger{
				background-color: red;
			}
			.info{
				background-color: skyblue;
			}
			.active{
				background-color: gold;
			}
		</style>
		<div id='app'>
            //You can use object binding, array binding, and one binding
            //The following true and false determine whether the style is displayed:
			<div v-bind:class="{active:flag,box:true}">wh</div>
			<div v-bind:class="['active','box']">wh</div>
			<div v-bind:class="[{active:flag},'box']"></div>
		</div>
		<script>
			new Vue({
				el: '#app',
				data: {
					flag:false,
					box:"active box"
				}
			})
		</script>

2. Bind style

	//Binding to style can also use a method, an array or an object
	//When binding style, write the style in the data
		<div id='app'>
			<div :style="box">=box</div>
			<div :style="{color:'blue',background:bg}">wh1</div>
			<div :style="[box1,box2]">wh2</div>
		</div>
		<script>
			new Vue({
				el: '#app',
				data: {
					bg:"pink",
					box:{
						color:"red"
					},
					box1:{
						width:"200px",
						height:"200px"
					},
					box2:{
						color:"red",
						background:"pink"
					}
				}
			})
		</script>

4, Data binding

1. Responsive data binding

Responsive: the page refreshes when the variable changes

In the way of data hijacking combined with publisher subscriber mode, hijack setter s and getter s of various properties through Object.defineProperty(), publish messages to subscribers when data changes, and trigger corresponding listening callbacks

2. Bidirectional data binding

Vue implements two-way data binding mainly by means of data hijacking combined with publisher subscriber mode, hijacking setters and getters of various properties through object. Defineproperty(), publishing messages to subscribers when data changes, and triggering corresponding listening callbacks. When a normal Javascript object is passed to the Vue instance as its data option, Vue will traverse its properties and convert them into getters / setters with Object.defineProperty. Users do not see getters / setters, but internally they let Vue track dependencies and notify changes when properties are accessed and modified.

5, Conditional rendering

v-if and v-show

v-if and v-else must be written together to implement

<div id="app">
        <button @click="change1">Exhibition</button>
        <div v-if="flag" >{{msg}}</div>
        <div v-show="flag" >{{msg}}</div>
        <div v-if="!flag" >{{msg1}}</div>
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                flag:"false",
                msg:"This is the first product",
                msg1:"This is the second item"
            },
            methods: {
                change1(){
                    this.flag = !this.flag
                }
            }
        })
    </script>

The difference between v-if and v-show

  • v-show hides elements through cs displa y: none

  • v-if is to destroy components to achieve hiding

  • Therefore, v-show has high rendering consumption and v-if has high switching consumption

  • Therefore, v-show is used for frequently switched services and v-if is used for infrequently switched services

6, Loop rendering

v-for will clone all the elements in the v-for tag, including its descendants. The number of clones is the length of the data array

If if and for are nested in the same layer, if will judge again when the data container changes
When the nested writing data container changes, if only judges the newly added data
In this way, when an item of data in the arr array changes, only v-if judgment is made on the newly added data, so as to save rendering efficiency

This will create a new problem: the div of the outer for will also create one to mount into the DOM
Solution: wx uses the block element, vue uses the template, which is actually the fragment in the dom operation, that is, create a meaningless empty tag to put v-for

The following is a case,

<div id='app'>
			<template v-for="el in arr">
				<h1>{{el}}</h1>							
			</template>
		</div>
		<script>
			new Vue({
				el: '#app',
				data: {
					arr:["a","b","c"]
				}
			})
		</script>

The meaning of key

When the number of container data in the for loop in data changes, it will be compared with the number of vm nodes in for
If there is too much data, the corresponding number of nodes will be added behind the vm node, and all nodes will not be recreated. Then the vm will update the corresponding DOM
Then refresh the data to the interface: render according to the data order in the data container of for. If the user has operated on the old node before, the new data order may not match the order of the old node (the old node does not correspond to the old data)
Solution: during the for loop, the data and the created node are used to bind the unique key value to the element

Brief answer: vue will compare the old node with the new vm node when refreshing the page component. If you want to add a node, the old node will not be deleted, but reused
This will cause the node to be re rendered without binding relationship with the data. You can bind the data to the node with the key

<div id='app'>
			<h1>Choose 3 items you like?</h1>
			<button @click="add">load</button> <br>
			<label v-for="(el,index) in goodsArr" :key="el.id">
				 <input type="checkbox"/>{{el.title}} <br/>
			</label>			
		</div>
		<script>
			new Vue({
				el: '#app',
				data: {
					goodsArr:[{id:5,title:"Bag"},
					{id:2,title:"shoes"},
					{id:3,title:"clothes"},
					{id:4,title:"Hat"}
					]
				},
				methods:{
					add(){
						let newgoods={title:"commodity"+(this.goodsArr[0].id+1),id:this.goodsArr[0].id+1}
						this.goodsArr.unshift(newgoods)
					}
				}
			})
		</script>

Posted by nike121 on Tue, 12 Oct 2021 10:36:47 -0700