#【2022.3】Silicon ValleyVue.js from Beginner to Mastery Basic Notes (Theory + Practical + Knowledge Points Quick Check)
preamble
This article is based entirely on Reference: processing and organization, including its code, cases, resources and so on. Pre-knowledge is to learn the video tutorials of the Silicon Valley, this article with its tutorials to eat, the effect is better.
Search for vue directly on the b-site and the first result will be:
/video/BV1Zy4y1K7SH?spm_id_from=333.
catalogs
I. General concepts, prior knowledge
1.1 MVC andMVVM
Everyone knows about MVC, but when you compare it with MVVM, you get confused. Here are two examples to clarify MVC and MVVM:
MVC architecture (back-end oriented, using JavaWeb as an example)
The architecture is the traditionalJavaWeb ProjectThe general pattern of development is relatively simple.
The following two images are taken from: and you can move directly to that blog for more details
MVVM architecture (front-end oriented, using Vue as an example)
The prerequisite knowledge is that you have to understand bidirectional binding: this article has the following explanation of bidirectional binding, first look at bidirectional binding.
A diagram to explain the MVVM (diagram source from the Shang Silicon Valley courseware, I carry out secondary processing):
Reflect the Data Bindings in the above figure in your code (via VM, binding M to View):
Reflect the DOM Listeners in the above figure in your code (via VM, binding V to M):
Implementation effects:
To do this at the same time as binding M to V, and V to M, is to realize a two-way binding.
The VM (that's ViewModel), which is actually the Vue instance itself, is responsible for binding the View to the Model
This is the MVVM embodiment of Vue! To understand it thoroughly, you need to have a detailed understanding of ViewModel, two-way binding, and Vue instances. Other front-end frameworks have different interpretations of MVVM, but the principles and ideas are the same.
Finally, look at Wikipedia's definition of it:
1.2 Basic WebPack Concepts and Vue-CLI
Do not need to learn all the WebPack this technology, just have a basic knowledge of it can be.
It relies onNodeYou can use thenpmInstallation;
Use the npm init command to build the file;
webpack can compile and package js and json files. Can convert es6 modular syntax into browser-recognizable syntax. Production environment can compress HTML, CSS, JS code.
Can package a variety of resources : style resources , image resources , HTML resources , extraction and compression of css , js syntax checking / compatibility processing .
What is Vue-CLI? It's actually the official Vue packaging build tool for .
1.3 [Interview] Virtual DOM (vitural dom)
The virtual DOM is the data in memory and then the virtual DOM is turned into the real DOM.
Native js (no virtual DOM):.
Vue uses a virtual DOM approach:
Benefits of virtual DOM: As shown above, if the technique of virtual DOM is used, it will compare the virtual DOM with the real DOM (It's the diff algorithm shown above) and realized that 001, 002, 003 are duplicates. So instead of rendering 001, 002, 003. again, it reuses them.
Only the virtual DOM of 004 is not duplicated and needs to be re-rendered. This improves presentation efficiency.
Virtual DOM and keys in v-for
The key in v-for is mentioned below.
The virtual DOM has a comparison algorithm based on what? It is based on the key
Here is a direct look at the correspondence:
When rendering, the old virtual DOM in memory is compared with the new virtual DOM based on the key, and once a change is found between virtual DOMs, only the changed part is re-rendered and the unchanged part is reused. So the key attribute is very important.
Once you have an input class DOM in your structure, an error DOM update will be generated, resulting in faulty rendering of the interface.
[Interview Summary] Summarize key and virtual DOM (react also has this concept)
1.4 Official vue documentation and APIs
/
The officially recommended Vue component package:
1.5 The concept of two-way binding
/weixin_44757863/article/details/109110132
1.6 Common tools and resources, websites, etc.
(Collection of numerous tripartite libraries, toolkits)
Vs Code Plugin: LiveServer
The plugin is truly a godsend. Built-in small Tomcat, running on a small server with the folder you open in VS as the root resource.
The default port number for this server is: 5050
As you can see in the two images below, you are just writing an HTML only, and it will run on the server localhost:5050 for you:
Vs Code Plugin: Auto Close Tag
Vs Code plugin: Auto Rename Tag
Other useful VS plugins:
JS Quick Console is a true godsend, quick generate() Doesn't it smell good?
Vue Devtools
When working with Vue, we recommend installing Vue Devtools on your browser. it allows you to review and debug Vue applications in a more user-friendly interface.
How to install:
Fixed the program (Google Chrome):
II. Vue Basic Notes
1. Installation (introduction)
Official website link:/v2/guide/
- 1.1 Native Installation: Introduced in HTML using JS tags You can use absolute and relative paths. If it is an absolute path, it is https://This direct introduction of Internet, if it is .../static this way, you can introduce your own downloaded files.Examples: - Vue-Cli
2. Create Vue objects, and Vue interpolation syntax { { xxx }}
The picture below shows it all in one picture:
Additional details about the above picture:
- 1, a vue instance, can only bind a corresponding instance. This is a one-to-one relationship. If you have more than one, you can't resolve it. - - - - - - - - - - - - - - - - - - - - - - -2. { {}} interpolation syntax, you can write JS expressions. (This is somewhat similar to thymeleaf) Look at the following example:
[Supplement] Two ways to write el and data (Vue instance management)
Another way to write el is as follows:
The reason for this is because the call to the prototype chain's$mount
Properties:
As for what a prototype chain is, it will be explained below. For now just remember that you can use this method to bind containers.
Another way to write data (functionally) is as follows:
Component-based development is all about functions. The function must return an object.
Note that this function, can only be written as a normal function. If you write it as an arrow function, the this of the arrow function is the window, and the this of the normal function is the Vue implementation object:
ES Grammar Mini-Class:
A normal function's this points to the object that called it, whereas an arrow function doesn't have a this, and if you force it to have a this, it ends up pointing to the window since no one called it.
The ES specification also allows you to abbreviate functions like this if you want to write them in objects (it's exactly the same thing as above, just abbreviated):
Like the data() above, in the future we can see a lot of functions managed by Vue (Vue objects will call it). Any function managed by Vue can't be written as an arrow function, it should be honestly written as a normal function!
Other configurable attributes when creating Vue objects
We have just introduced only el and data, and we will continue to introduce the others here.
[methods] can pass a variety of functions.
But this function is still managed by Vue, so it can't be written as an arrow function, only as a normal function.
mods is an object into which you can pass all sorts of functions.
The incoming function should conform to the syntax rule: a property of a JS object is a function. You can search on your own how to make a property of a JS object a function.
Examples:
event in methods
event when not using Vue.invocations
In Vue, if you don't pass any parameters, the function in methods can automatically get the event:
In Vue, if you want to pass a real event object (event is a global object built into the browser), you can't write event directly, instead you should write: $event
If you want to use event, there is a [real parameter] placeholder$event
The event can be passed in as a formal parameter:
Important] methods calls data configuration properties.
Just use this.
The red arrow is using this to get to the value of data.But the brilliance lies in the blue arrows, because the blue arrows use v-models, which take on the attributes of the DATAtwo-way bindingThen once the input box changes, it causes the data to change, and the data changes cause the return value of the custom function in methods to change!
computed The computed property
watch The watch attribute
filters Filters
template HTML template
The diagram below shows the simplest usage
3, Vue directive syntax
Having previously covered the Vue interpolation syntax in 2 { {}}, and here's the directive syntax. This piece is much more like thymeleaf, just bind directly to the tag.
[v-bind]: Bind html tag attributes:
v-bind can be directly abbreviated as : (a colon) v-bind: followed by double quotes, the same as { {}} interpolation syntax to write JS expressions.As with thymeleaf, v-bind: can bind any tag.
[v-model] Bidirectional binding:
/weixin_44757863/article/details/109110132
Two additional notes:
1. The following figure 2、v-model:value
The abbreviation forv-model
. The reason for this is simply because v-models can only be applied to form classes (input class elements).
Example:
Difference between command syntax and interpolation syntax:
Interpolation syntax for labeled bodies, example:
<p>Hello,{<!-- -->{name}}</p>
- 1
- 2
Instead, the command syntax is tied directly to the custom attributes of the tag, Example:
<a v-bind:href="defineUrl" v-bind:xxxx="hello"> hyperlink</a>
- 1
- 2
4. Methodology
A more advanced way of adding properties to an object. Much more advanced than this original method and can be configured with a lot of detailed information.
Usage is shown in the following figure, more detailed configuration object properties can be Baidu.
If it is set not to be enumerable [the default is not to be enumerable! , then you can't use a for-each loop to traverse object properties.
- Common property: enumerable, boolean, default value is false, if you want the field to be enumerable, set it to true explicitly. - Common attribute: configurable, boolean, default value is false, controls whether the field can be deleted. - Common property: writable, boolean, default value is false, controls whether the field can be modified. - Commonly used attributes: value, is to assign, assign a value to the field.
Common properties of get and set
The get and set properties are particularly important, so they are covered in a separate section.
Take a look at the following scenario:
let number = 18
let person = {<! -- -->
name: "Daikichi",
sex: "male",
age: number
}
() // output 18
number = 22 //change the number variable to 22
() //Output is still 18, not 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
What if we want the second output to be 22? What should we do?
Here's where our powerful get and set functions are introduced!
- Picking up on the example above, use get to change the output to 22:
let number = 18
let person = {<! -- -->
name: "Daikichi",
sex: "male",
age: number
}
() // output 18
(person, "age", {<! ---->
get() {<! ---->
('Someone read the age attribute')
return number; //return values are important
}
})
number = 22 //change the variable number to 22
Whenever someone reads the age attribute, the get method is called.
get method is called, and the value returned by the get method is the number variable.
() //22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
The execution effect is shown in the figure:
So with get, we've implemented a method that executes get whenever someone reads the age attribute, and as far as the get method is concerned you can stuff whatever you want in there. Anyway, as soon as someone reads the age attribute, get is executed.
- Here's another look at the set method:
let number = 18
let person = {<! -- -->
name: "Daikichi",
sex: "male",
age: number
}
("The value of number is: " + number) //18
(person, "age", {<! -->
// Whenever someone modifies the age property
// then the set method will be called and will receive the specific value of the modified age attribute
set(value) {<! -->
('Someone modified the age attribute, age:' + value)
// Here's the magic operation, we make the variable number modified
number = value;
}
})
= 22 //Modify the age attribute, thus calling the set method
//It's amazing that we can make changes to number when we've obviously modified age.
("The value of number is: " + number) ///22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
Execution Effect Diagram:
In summary: get and set make manipulating objects more flexible
Why learn this method? It's to prepare for the next section on data proxies!
5. Data proxies (data hijacking)
Concept: Data proxying is the manipulation (read/write) of attributes in one object by another object.
Look directly at the picture below:
If someone moves obj2 in the above diagram, it is equivalent to moving obj through obj2. This is the simplest example of data proxying
How does Vue apply data proxies?
Through the data proxy, we should have operatedvm._data.properties
Now we're going to do it directly.vm.properties
Ready to go.
6. Incident handling
6.1 [v-on] Binding Click Events(in conjunction with the methods lecture earlier)
The abbreviation is @ symbol
Example: (The following two ways are equivalent.)
<button v-on:click="func1"> button</button>
<button @click="func1"> button</button>
- 1
- 2
If you want to pass a parameter (and of course you need to define the formal parameter at the definition of func1 to do so):
<button v-on:click="func1(a,b,c,d)"> button</button>
- 1
- 2
How will func1 and func2 be managed by Vue? Move to methods in the previous section and find out.
6.2 Event Modifiers
To operate on events, the prerequisite knowledge is that you have to know event in JS.
JS basic event
/lhjuejiang/article/details/79455801
event is a built-in global object, so let's see what's inside:
<button onclick="func1(event)">buttons</button>
function func1(event) {<!-- -->
console.log("I am a function.")
console.log(event.target)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
The above code calls func1 and passes in the global event, see the properties of event below:
Common poses for EVENT:
()
It prevents default events from occurring. For example<a>
tag, whose default event is a jump. If we want to prevent jumping on clicking a hyperlink, we can play around with it like this:
<a href="" onclick="func0(event)">hyperlink, link</a>
function func0(event) {<!-- -->
()
}
- 1
- 2
- 3
- 4
- 5
- 6
Open the console at this point:
The defaultPrevent property of event was false by default and is now true. Now clicking on a hyperlink will not jump.
Coming back to the event modifier, what do we need to do if we want to implement the above in Vue? The event modifier will be right on the scene:
<div >
<a href="" @="func00(event)">Managed hyperlinks by Vue</a>
</div>
<script>
new Vue({<! -- -->
el: '#root', }
data: {<! -- -->
}, methods: {<!
methods: {<! -- --> }, methods: {<!
func00(event) {<;! ---->
("vue blocking page jump")
}
}
})
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
The pile of code above, and the() It's the same effect.
@
is an event modifier.
Common event modifiers (six in total):
prevent、stop、once、capture、self、passive
stop prevents the event from bubbling up to the level above it; once: if once is applied to a button or a hyperlink, then the hyperlink will only jump the first time it is clicked, otherwise the hyperlink will not jump.
Keyboard Events
Take the @When Keyboard Picks Up event as an example:
If there is a keyup, there is a keydown, and when the keyboard is pressed, an event is triggered immediately. upper@
That is, when the esc key pops up, it triggers the custom function showInfo (which must be managed by Vue, i.e. in methods)
Other common key aliases: Explanation 2 of the above figure: If you want to bind CapsLock, you should write it like this:@-lock="xxxFunction"
The name of the organization is the same as the name in lowercase with a short horizontal line.
[DEBUG:] It seems that the function bound by the event modifier here can't be written xxxFunction() followed by parentheses. Otherwise it will report an error. The parentheses must be removed for this to work.
7. Calculated properties (computed)
Problems to be solved by computing properties
The problem to be solved by the compute property is that the interpolation syntax { {}} with increasingly long JS expressions that are not conducive to readability and componentization.
Come see the case:
Calculating Property Use Cases
The compute property is linked to data, again using this. see the example below:
The firstName and lastName in the input box above and the firstName and lastName in the data box below are bi-directional bindings.
When the input box changes, so does the data. If someone calls fullName in the calculated property at this point, then fullName will naturally change.
There is another attribute of get in the computed properties: whenever the data bound to get changes, it is also equivalent to a call to get() in vm, so whenever the firstName and lastName in data change, then fullName is called.
Execution Effect Diagram:
By the way, the computed attribute also has a set, which is used in the same way as the set, as shown in the following figure
Calculate the property summary:
Why is it called Calculated Properties? It is based on thedata
in the complex properties calculated from the properties that are already there.
Calculated Property Abbreviations
When you have a computed property that is only read by humans and not modified by humans, (i.e., only get and not set), then the computed property can be abbreviated as:
The above is equivalent to the following code (which is really just a shorthand for get, computed is an object, and the fullName field of the object is just a function):
computed: {<!-- -->
fullName: {<!-- -->
get() {<!-- -->
('getwas called')
return + '-' +
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
8. Monitoring properties (watch)
Conceptual Role: Monitoring attributes is still about monitoring changes to the attributes of data.(You can also monitor the calculation properties!)。
The passed value of the monitor property is a configuration object.
When a field inside the data changes, call the handler function, the handler function has two inputs, respectively, newValue, oldValue, as the name implies, on behalf of the modification before and after the modification. As shown in the figure below:
If the monitored structure is multilevel:
data:{<!-- -->
numbers:{<!-- -->
a:1,
b:1
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Then it should be configured like this:
watch: {<! ---->
'': {<! ----> //configure the multilevel structure this way
handler() {<! -- -->
("a was changed.")
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Other ways to write the monitor attribute:
Calls the vm's $watch method:
This writing can be abbreviated. HoweverThe premise of the abbreviation is: the configuration item of watch only has one parameter, handler !!!! and there can't be any DEEP, IMMEDIATE or anything like that.
Abbreviated approach:
Abbreviations for monitoring attributes
The shorthand presupposes that the watch configuration item has only one parameter, handler !!!!
immediate :true Let the handler be called on initialization. You can't write "immediate" or "deep" to use this abbreviation.
deep monitoring
Deep Monitoring is turned off by default.
The scene is as follows:
If the monitored structure is multilevel:
data:{<!-- -->
numbers:{<!-- -->
a:1,
b:1
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
If you want to monitor changes, you've already done so above. I won't explain it here. But if a changes, then numbers should also change.But Vue doesn't think that numbers has changed! At this point you monitor numbers again, and if it's been changed, then Vue doesn't think numbers has been changed.
As shown below:
watch: {<! ---->
numbers: {<! ---->
handler() {<! ---->
// Even if it's changed, the next sentence won't be executed
("numbers was changed.")
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Solution: Turn on Deep Monitoring:
watch: {<! ---->
numbers: {<! ---->
handler() {<! -- -->
deep:true, //Enable deep monitoring
// Changed, the next sentence will be executed
("numbers was changed.")
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
Deep Surveillance Summary;
Summarizing watch and computed
If it is required to be asynchronous, use watch. because computed depends on get and return values.
All functions that are managed by Vue, please write them as normal functions. Because you need to make this point to vm
All functions that are not managed by vue, such as the various callback functions (timer callbacks, ajax callbacks, promise callbacks), are best written as arrow functions. This is so that this points to what they are supposed to point to. If you write it as a normal function, it will cause the call to fail, because your this points to the vm
Therefore, whether to write a normal function or an arrow function requires determining who this points to. If you need this to point to the vm, you must write a normal function, otherwise (if you need this to point to another caller) use an arrow function.
9、v-bind bind class, style style
A. Binding class
It's really just v-bind to a class.
It can be written as an array, as below, as a field; or as an object.
Three different ways to write:
Write as a field, and write as an array are demonstrated first:
The final demo is written as an object (with true and false determining whether the properties within the object are in effect or not):
B. Binding style
-
(Common) object writing
As shown in the figure below, the attribute fields inside the object write method cannot be written blindly, and need to be written with underscore to camel:
10. Conditional rendering (v-if, v-else, v-show)
A, v-show (control whether to display or not)
v-show can only receive boolean types (either directly true, false; or expressions of type true and false):
<h1 v-show="1 === 3">Daikichi</h1>
If you write it this way, the h1 tag will be hidden, because the value inside is false
It is also possible to write attributes of type true/false inside data:
The element that v-show hides away is just stylistically hidden from view, but the element is still there (invisible = true). But the v-if below is just killed.
B、v-if
Consistent with v-show usage, fill in a boolean expression.
But unlike show, the element is taken out straight away, rather than stylistically hidden.
C、v-else-if 、v-else
A picture will tell you:
If there is an element between conditional judgments that breaks them:
Then the latter is not in effect.
D. Summary
11、List rendering related
11.1 v-for
The simplest example:
The formal parameter can also be two parameters: as shown below;
The second parameter fixed is the index:
v-for can also traverse objects (the 2nd argument here would not be an index, the two arguments are value and key):
11.2 key (frequently asked in interviews)
When using a for loop, whether it's vue or react, you should give each html element generated by traversal a name. This is the key
****
Examples:
The key can also be filled with index:
If you don't write the key, then there is a chance that you will have problems with rendering errors. Why does this problem occur? Because the key is related to the virtual dom.
****
Finally, look at the official definition:
11.3 List filtering (fuzzy search)
Scene:
Overwatch's implementation scheme:
The following code difficulties are as follows:
- immediate :true Let the handler be called on initialization. - JS Basics: Using Array filter - JS Basics: Using indexOf
The above code probably works:
- 1, use v-model to bind the elements in the input box to the keyWord of the data - 2, use watch to monitor the keyWord, once the keyWord is changed, filter the keyword immediately - 3, once the keyWord is changed, filter the keyword and return a brand new array, which is assigned to the keyPerson of the data - 4, filPerson is responsible for being traversed by the front-end v-for to display the result after filtering (after fuzzy query). filPerson - 4. filPerson is responsible for being traversed by the front-end v-for to display the filtered (fuzzy query) results.
Use computed to implement the above functionality
The above code probably works:
- 1. Use v-model to make the elements in the input box bind to the keyWord of the data.2, the use of filter, input box changes caused by keyword changes caused by changes in persons - 3, establish the calculation attribute filPersons, when there is a change in the persons, then recalculate the filPersons once again. - 4, filPersons is responsible for being traversed by the front-end v-for, displaying the filtered (after the fuzzy query) result
11.5 [Important! Interview Question] Principle of Vue Detecting Data Changes
The version of vue introduced by the demo in this chapter is (2.4.1), if the version is too new it will report an error:
<! -- Introducing Vue -->
<script src="/npm/[email protected]/dist/"> </script>
- 1
- 2
- 3
Introducing:
Requirement: Click the button to edit only the information of Ma Dongmei:
Code Writing:
In the code above: mode 1 works, mode 2 does not. Why is this? Does Vue not recognize way 2?
Cause analysis:
Direct assignment is not considered responsive by vue.
Solution 1:
Instead of seeking to modify individual elements of the array, replace the entire array. Something like this:
= {<! ---->
{<! ----> id:001, name:'Mr. Ma',age:50,sex:'Male'}, //replace the item
{<! ---->id:002, name:'Zhou Dongyu',age:33,sex:'male'},
{<! -->id:003, name:'Jay Chou',age:33,sex:'male'}, {<!
{<! ---->id:004, name:'Zhou Dongyu',age:33,sex:'male'}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Replacement of arrays This can be achieved here with filter, concat, and slice:
Solution 2 (Use the array change method):
![Insert image description here](/?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQOWkp-WQiQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
hift({<!-- --> name: "jack", age: 70 })
- 1
- 2
- 3
- 4
To operate on an Array, and to have the Array still be responsive, you must use the seven methods that Vue gives us built-in:
With so many ways to manipulate arrays in native JS, why are these 7 the only ones encapsulated by Vue? Because these 7 elements will change the native array. The basis of judgment is whether the method will change the native array!
Why does the above solution work? Because Vue encapsulates the common methods of arrays for us:
push、pop、shift、unshift、splice、sort、reverse
vm's push is not the same as Array's push method. vue does two things for us:
- 1. Calls the native array push-2, trigger the view (viewmodel) of the update
Using this approach to increment and change Array elements, you can use the = equals sign to assign values to objects in them, and their assignments will still be responsive! You don't have to use vue's built-in set method!
Use Vue's built-in set method to add properties that the data object doesn't have
What if your dom wants to add a property that vue's data doesn't have? Note that you're adding what's not there, not modifying what's there.
To add one that wasn't there before, we have to use the built-in set method to add one, based on the principle of Vue detecting data changes above.Responsive data attribute.
Straight to the case: click the button to add the data attribute to the vm and display it:
This can be achieved by using.
Never use: = "male" in this way!
The basis for determining whether a property is truly responsive is whether or not it has a getter and setter (the image below is responsive):
In summary: Vue detects data change principles
The full demo code for this chapter is shown below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <html lang="en"> <head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>.
<div > <button @click; <button @click; <button @click
<button @click="++">Age +1 year</button> <br />
<button @click="addSex">Add the gender attribute</button> <br />
<button @click=" = 'Unknown' ">Modify the gender attribute </button> <br />
<button @click="addFriend">Adds a friend to the top of the list</button> <br />
<button @click="updateFirstFriendName">Change the name of the first friend to: Zhang San</button> <br />
<button @click="addHobby">Add a hobby</button> <br />
<button @click="updateFirstHobby">Change the first hobby to: driving</button> <br />
<h3> Name: {<! ---->{}}</h3>
<h3>Age: {<! -- -->{}}</h3>
<! -- This tag will only be shown if vm._data has a gender -->
<h3 v-show=""> Gender: {<! -->{}}</h3>
<ul>
<li v-for="(h,index) in " :key="index">
{<! -- -->{h}}
</li>
</ul>
<h3> Friends </h3>
<ul>
<li v-for="(f,index) in " :key="index">
{<! -- -->{}} -- {<! ---->{}}
</li>
</ul>
</div>
</body>.
<! -- Introducing Vue -->
<script src="/npm/[email protected]/dist/"> </script>
<script>
// Create the Vue instance
const vm = new Vue({<! ---->
el: '#root',
data: {<! ---->
student: {<! -- -->
name: 'Daikichi',
name: "Daikichi", age: 18,
hobby: ["Smoking", "Drinking", "Hot hair"],
friends: [
{<! ----> name: "friends1", age: 35 }, friends: [ {<!
{<! -- --> name: "friends2", age: 36 }
}
}
}, methods: {<!
methods: {<! ---->
addSex() {<! ---->
debugger.
//(, 'sex', 'male') // way 1, must do this to be responsive
this.$set(, 'sex', 'male') // way 2, must do this to be responsive
},
addFriend() {<! ---->
({<! ----> name: "jack", age: 70 }) //must do this to be responsive
},
updateFirstFriendName() {<! ---->
[0].name = "Zhangsan"
},
addHobby() {<! ---->
("Study")
},
updFirstHobby() {<! -- -->
(0, 1, "Drive")
}
}
}).
</script>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
12, Vue collect form data
Radio Box (Special) Binding Techniques
If the input type is a radio (checkbox), this is more specific:
<!-- v-model Collection onlyvalue(be) worth -->
male<input type="radio" v-model="sex" value="male" name="sex">
women<input type="radio" v-model="sex" value="male" name="sex"> <br /><br />
- 1
- 2
- 3
- 4
Requires the v-model to bind the data attribute while specifying the value value (values can be equal)
Multi-Checkbox (Special) Binding Techniques
If the input type is a checkbox, this is special:
It must be ensured that the bound data data is an array, and a different value must be specified:
Why is it an array? Because it's a multi-check box, it's going to be multiple choices! It must be an array!
The effect is as shown (why it must be received in an array):
Dropdown Box Binding Tips
If the input type is a select and option (drop-down box)
Because option has a value attribute inside, it only needs to be bound to select (option only needs to write the value, which will interact with the vm):
<select v-model="city">
<option>Please select a campus</option>
<option value="beijing">Beijing, capital of People's *</option>
<option value="shanghai">Shanghai</option>
<option value="shenzhen">Shenzhen subprovincial city in Guangdong, special economic zone close *</option>
<option value="wuhan">Wuhan city on Changjiang, subprovincial city and capital of Hubei province</option>
</select>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
v-model Special Usage
Remove the spaces before and after and justReady to go:
summarize
All demo code:
Effect:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<div >
<form>
username:<input type="text" v-model="name"> <br /><br />
cryptographic:<input type="text" v-model="password"> <br /><br />
distinguishing between the sexes:
<!-- v-model Collection onlyvalue(be) worth -->
male<input type="radio" v-model="sex" value="male" name="sex">
daughter<input type="radio" v-model="sex" value="female" name="sex"> <br /><br />
take pleasure in:
do<input type="checkbox" v-model="hobby" value="study">
play a game<input type="checkbox" v-model="hobby" value="game">
dine<input type="checkbox" v-model="hobby" value="eat">
<br /><br />
school district:
<select v-model="city">
<option>请选择school district</option>
<option value="beijing">Beijing, capital of People's *</option>
<option value="shanghai">Shanghai</option>
<option value="shenzhen">Shenzhen subprovincial city in Guangdong, special economic zone close *</option>
<option value="wuhan">Wuhan city on Changjiang, subprovincial city and capital of Hubei province</option>
</select>
<br /><br />
Other information:
<textarea></textarea> <br /><br />
<input type="checkbox" v-model="agree">Read and accept<a href="">《user agreement》</a>
<button>submit (a report etc)</button>
</form>
</div>
<body>
</body>
<script src="/npm/[email protected]/dist/"></script>
<script>
const vm = new Vue({<!-- -->
el: '#root',
data: {<!-- -->
name: "",
password: "",
sex: "male", //默认是male
hobby: [],
city: "beijing",
other: "",
agree: ""
}
});
</script>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
13. Vue filter (Linux(the pipeline character |)
The functionality that can be achieved in this chapter is fully realized using METHOD, and COMPUTED, except that filters can be further simplified.
Look directly at the example:
Filter Passing Parameters
If only one parameter is passed, then the default must be the element before the pipeline character (well understood, it's the same as the linux pipeline character)
But filters can also be passed multiple parameters:
The first of these parameters, must be the element in front of the pipeline character, only the second parameter is a customized parameter:
Global and local filters
Previously written as a localized filter, only one vm works.
The following figure shows the global filter:
14, Vue commonly used other built-in instructions (simple)
Previously learned commands:
v-text
v-html (problems associated with dynamically rendered HTML)
More advanced than v-text: can parse html tags:
The effect is as follows:
But this method is risky:
Dynamically rendering HTML on a website is very dangerous and can easily lead to XSS attacks! , such as stealing cookies!
Supplementary knowledge] Cookie mechanism and xss attacks
cookie mechanism
Cross-browser reading of cookies is not valid:
It contains our user information, permission checking and various other information.
This also explains that using postman to call some web interfaces does not work, you have to have a cookie to call through.
And cookies contain a set of permission checking information.
Viewing cookies As shown below:
That is to say: if someone learns all the information about our cookies for a particular website and sets them to that person's browser, then that person can log into your account without having to log in!
xss attack:
An XSS attack is a way to "instigate" the user's browser to execute some front-end code that doesn't exist on the page.
for example, by usingcommand to steal the user's cookie information!
v-cloak (n. cloak vt. cover; conceal)
JS blocking
As shown below, if the JS code is introduced outside the body:
Once the link is blocked, the above image blocks the entire browser for 5 seconds, waiting for the JS to load all the way out before rendering the interface!
But if JS is introduced like in the image below:
The v-cloak role is used in conjunction with css. The v-cloak tag is automatically removed until the JS blocks (doesn't load out). In other words, as soon as it loads out, then the v-cloak tag does not exist.
In the above image, if you encounter JS blocking, h2 will be controlled by css and not displayed. Once loaded out, the v-clock will not exist. Thus, the CSS code is disabled and h2 will be displayed.
v-once (dynamic rendering only once)
v-pre
vue does not parse nodes with v-pre. This node should not be used indiscriminately, but only when optimizing performance
15, Vue custom directives
Demand:
Functional designation (fulfillment of requirement 1)
Debug's uppercase hump nomenclature:
So in the official style guide, if you come across a long word, don't use a hump, use a short horizontal line.
Object-based designation (fulfillment of requirement 2)
Object-based designation is more advanced, as it does everything that function-based designation does, and also allows you to customize the timing of the call.
object-style specification, you must write the function name that Vue gives us, otherwise it will not be parsed. There are three common function names: bind, inserted, and update.
The three functions above (bind, inserted, update), their formal parameters can receive the [functional specification] said element and binding of the two formal parameters.
The three methods, bind, inserted, and update, are the three different moments of vue parsing. At each of the different moments of vue parsing, vue will call one of these three different functions for us.
Global Customization Directive and Local Customization Directive
Functional designation of the global:
Object-style specifies global:
The difference is simply whether the second argument is passed as an object or a function.
summarize
16、【Interview】vue lifecycle function (also known as hooks)
react has a similar hook concept to vue's
Introducing:
Requirement: make an effect of this:Mode 1 (not recommended):
The following approach relies on the formal parameter vm. It's not integrated into the Vue initialization.
<body>
<div >
<h2 :style="styleObj"> Welcome to vue</h2>
</div>
</body>
<script src="/npm/[email protected]/dist/"> </script>
<script> </script
const vm = new Vue({<! ---->
el: '#root',
data: {<! -- -->
styleObj: {<! -- -->
//opacity is the style's style, which controls transparency.
opacity: 0.5, color: "orange
color: "orange"
}
}
});
// Way 1: by manipulating the style of the vm (not recommended)
setInterval(() => {<! -- -->
-= 0.01
if ( <= 0) = 1
}, 16);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
Way 2: destroys the original requirement (requires a click to trigger)
Neither of the above methods can fulfill the requirement, the following uses mounted to fulfill the requirement:
mounted (mounted):
Concept: vue will call mounted after it finishes parsing the template and puts the initial real DOM elements into the page (after mounting is complete). mounted will only be called once.
Use mounted to accomplish the above requirements:
<body>
<div >
<h2 :style="styleObj"> Welcome to vue</h2>
</div>
</body>
<script src="/npm/[email protected]/dist/"> </script>
<script> </script
const vm = new Vue({<! ---->
el: '#root',
data: {<! -- -->
styleObj: {<! -- -->
//opacity is the style's style, which controls transparency.
opacity: 0.5, color: "orange
color: "orange"
}
}, //opacity is the style responsible for controlling transparency.
methods: {<! ---->
}, mounted() {<!
mounted() {<! ---->
("The vue template is parsed and will call me once!")
setInterval(() => {<! ---->
-= 0.01
if ( <= 0) = 1
}, 16);
},
}).
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
Perfectly realized!
By looking at the above usage of mounted, you can see that mounted is in fact an ordinary function. This function is called when the DOM is loaded and will only be called once.
mounted is a vue lifecycle function.
The problem of this for lifecycle functions:
The this of the lifecycle function is already maintained to refer to the vm. So inside, if there is a function form parameter that needs to be used that will be passed to an arrow function (such as setInterval above, where the first parameter is an arrow function), you should write the arrow function! The this inside that arrow function will then find the vm itself!
Other life cycle functions
Sourced from the official website's life cycle illustration:
Shang Silicon Valley explains further:
The red boxes in the image above are all lifecycle functions (which can be called like mounted)
vm.$destroy()
Used to completely destroy a vue instance.
Hook-to-hook variable passing tip (local variable to global variable)
Using the fact that the this of a hook function means the vm itself, you can hook local variables to the vm, so that local variables between hooks become shared global variables
Example:
Solution: hook the variable id to the vm and it becomes global:
Routing-related hook functions
The prior knowledge is routing, move to the Routing chapter.
summarize
In fact, the two hooks that get the most use are mounted and beforeDestroy.
Vue componentized development
1、Component base concept
The pain points of developing the traditional way and the benefits of introducing components:
Relationship of vm objects and components:
First, there is only one vm object. The rest are components, which are also known as small vm's and have some vm functionality:
2. Non-single file components (is prior knowledge)
Learn this first.
utilization
Creating Components
The configuration objects passed in there are almost identical to the configuration items passed in when new Vue was created, but there are a few things to note below:
- Be sure not to write el configuration items. This is because the definition of a component dictates that the component acts as a brick in modular development, moving wherever it is needed. So the component is not responsible to any parent component, only to the vm itself. - data must be written as a function, otherwise it will report an error. The reason is the same as above, if the component is referenced many times, writing it as a function can ensure local encapsulation. - Rendering html using template.Note that the html inside the template can only have one root element.- Components are categorized into local and global components. Registering a global component only requires the
('Component name', location of the component to be registered)
can be used. Usually these two parameters are the same
Creating a Component Trilogy:
The code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <html lang="en"> <head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>.
<body> <div >
<! -- Step 3: Write component tags in root -- >
<xuexiao> </xuexiao>
<xuesheng></xuesheng>
</div>; </body>.
</body>.
<script src="/npm/[email protected]/dist/"> </script>
<script> </script
// Step 1: Create component 1
const student = ({<! ---->
// Use template to draw out the html (componentization). Note that the html within template can only have one root element.
template: `
<div>
<h2> name: {<! ---->{name}}</h2>
<h2>Age: {<! -- -->{age}}</h2>
</div>
`,
data() {<! -- -->
return {<! -- -->
name: "Daikichi",
age: "18"
}
}, }
})
// Step 1: Create component 2
const school = ({<! -->
template: `
<div>.
<h2> address: {<! -- -->{address}}</h2>
</div>
`, {< {< {address}}
data() {<! ---->
return {<! -- -->
address: "Beijing"
}
}, }
})
const vm = new Vue({<! ---->
el: '#root',
// Step 2: vm registers the components (localized registration)
components: {<! -- -->
xuexiao: school,
xuesheng: student
}
});
</script>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
The rendering is as follows:
Non-single file component notes (debug):
- Component name case issues will report errors. Be careful.- Component names and HTML elements cannot be renamed.- You can use the name field to specify the component's name in theDeveloper Toolsin the name (only fools the developer tools)
Component shorthand (just write the configuration object directly)
The following two ways of writing are equivalent!
Nesting of components
The following figure shows that there is a nested relationship between components.
Mission Objective:
In the Vue developer tools, implement the nested structure shown below:[Note]: In standardized development, we will create a component that is only responsible for managing the component, not for rendering data. In other words, this component assumes the role of a manager and is responsible only to the vm (root). In the above figure, the app component assumes the above role.
Code Implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <html lang="en"> <head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>.
<body> <div >
<! -- Nothing to write! -->
</div>
</body>
<script src="/npm/[email protected]/dist/"> </script>
<script>
//student is written above, school below. To prevent school from referencing son
const student = ({<! -->
template: `
<div>
<h2> name: {<! -- -->{name}}</h2>
<h2>Age: {<! -- -->{age}}</h2>
</div>
`,
data() {<! -- -->
return {<! -- -->
name: "Daikichi",
age: "18"
}
}, }
})
//school and student are parent-child relationships
const school = ({<! -->
template: `
<div>
<h2> address: {<! -- -->{address}}</h2>
<student></student>
</div>
`,
data() {<! -- -->
return {<! -- -->
address: "Beijing"
}
},
components: {<! ----> //Sleeve, bringing in the son, student.
student
}
})
//hello and school are related on an equal level
const hello = ({<! -->
template: `
<div>
<h2> {<! -- -->{hello}}</h2>
</div>
`, {< -->{hello}}
data() {<! ---->
return {<! -- -->
hello: "hello"
}
}, }
})
// The manager of the component, app (the component that is only responsible to the vm, one person and all people)
// The component is not responsible for any rendering.
const app = ({<! ---->
/* Never forget to wrap school and hello in divs below, because there can only be one root */
template: `
<div>
<school> </school>
<hello></hello>
</div>.
`,
components: {<! ---->
--> --> school,
school, school, hello.
}
})
const vm = new Vue({<! ---->
el: '#root',
template: `
<app> </app>.
`,, `.
// Step 2: vm registers components (local registration)
components: {<! -->
--> app
}
}).
</script>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
VueComponent constructor
What is a component? What happens if we export a component?
It turns out that it is actually a function, to be precise he is a constructor.
- Special note: Each time `` is called, a brand new ViewComponent is returned! **this in vc, pointing to vc itself; this in vm, pointing to vm itself; **[Extremely Important, Interview] Vue Prototype Chaining, and Built-in Relationships
The relationship between Vue and vm
Vue is a function and vm is its new instance object
Therefore.vm.__proto__ ===
Relationship between VueComponent and VueComponent instance objects
VueComponent is a function and a VueComponent instance object is an object
When rendering the VueComponent, the VueComponent instance object is automatically newed
So:VueComponent instance object . ___proto___=== . __proto__
With the above laid out, Vue has an important built-in relationship:
-
.__proto__ ===
- So:VueComponent instance object . __proto__ === . __proto__ === vm.__proto__ === .
- The reason for this built-in relationship is to give VueComponent instance objects access to the properties and methods of Vue prototypes.
[Addition]: JS prototype related knowledge: Note: Explicit prototype attributes are only available for functions, not for objects! Objects have only implicit prototype attributes!
So, function.prototype is an object. It traces the prototype chain further up the chain, and can only look for__proto___
(modal particle intensifying preceding clause)
consequently.__proto__ ===
, objects === objects, this equation holds.
So (that is)vm.__proto__
) What's in it? There are lifecycle functions (mount, watch, etc.):
Keep going.
The prototype attribute of a function instance (Function objects. __proto___
), always points to the prototype object of its creator (function) (function.prototype
)
The end of the prototype chain is Object, and the prototype property of the Object instance points to null. this is the end of the prototype chain
The green arrows in the figure below, then, reflect the above prototypical chain relationships:
Last picture:
What Vue does this for: to give VueComponent access to the properties and methods of the Vue prototype.
3. Single-file components (.vue)
The prerequisite knowledge is non-single file components, and that chapter is required. Otherwise, you won't understand it.
Grammar Overview
Expose components using the default exposure method (ES6 modularity knowledge):
- Default Exposure
The code above can be abbreviated directly to:
Note: As shown above, the name field must be the same as the filename. This is the rule of thumb.
Manager of components, entry components
Remember the app component mentioned above when talking about single file components?
In Vue modular development, there is indeed such a component:
The app component is written as follows:
The app component has been a one-man show. So that brings us to the entry component, which is the vm:
In vue modular development, use as an entry component which is responsible for introducing (manager components):
In the html page, just prepare a div with id root and introduce , then you can.
4、Vue-CLI (Command Line Interface)
vue scaffolding is a standardized development tool (development platform) officially provided by vue
It's actually an official version of webpack!
Official document: /zh/
Installation of the CLI, creation of startup projects using the CLI
NODEJS: Replacing Taobao Mirror Source
npm config set registry
Execute the command to install the CLI:
npm install -g @vue/cli
How to create a project with this scaffolding:
- cd to the directory you want to create - execute the command:
vue create project name
- Manually choose whether to create a Vue2 or Vue3 version (here choose Vue2) - cd to the created project and execute the command:npm rum serve
As you can see above, a built-in Tomcat is up, and you can get your Vue project by directly accessing localhost:8080.Here's the magic: the following string of addresses Network, if your colleagues (in a LAN environment) entered, can also get to your Vue project!
Analyzing Scaffolding Catalog Structures
configuration file
- The node know-how, which conforms to the NPM configuration specification will have this file. The short commands inside web-pack are also in there. - Configuration file for babel involving ES6 to ES5 conversion -
Package version control files. Includes plug-ins, resource files, and so on.
The function is to install to the specified version as fast as possible, the version locking function is locked in this file.
Other catalogs
- It's the entry component described above. When the
npm run serve
Executed. It's executed.
Other notes:
- The path problem of the
BASE_url is built-in and actually refers to the . /public directory
Introducing static resource files (e.g. methods)
Summary document structure
About vue scaffolding configuration file modification
Turn off vue syntax checking/grammar detection:
Configured in:
lintOnSave:false
5、Component development of other related properties
5.1 The render function (meaning render)
render Provide, submit, render
The native way to write the render function
By writing it natively, we can see that it is actually equivalent to the functionality of creating templates and components in the vm samples in the previous study of non-single file components.
But we don't usually write render this way, instead we use the abbreviated writing style:
It actually helps us create templates and load components.
Why use render? Because vue-cli loads the running version of Vue by default, it doesn't recognize the template and components tags, so you can only use render.
5.2 The $refs Attribute
summarize
In Vue, if you want to take the Dom element, it's not elegant to use the method shown below:
The Vue solution is also simple: set a $refs property that is bound to the VueComponent instance object (vc):
If bound to a native HTML tag, it essentially adds an id attribute to it (the following image is equivalent to the one above)
[Important] ref binding component label
What if ref binds a component? Then get the vc of that subcomponent.
The app's vc has a
r
- 1
e
f
be born in the year of (one of the 12 animals)
suffix forming noun from adjective, corresponding -ness or -ity
,
ref attribute.
ref属性,ref属性上有一个该子组件的vc
Summary:
5.3 props configuration item (important, can be used to transfer data between parent and child components)
If it is not a parent-child component, there are other ways to transfer data.
Demand is introduced:
A component is shown below.
We want to create two students in the following figure, each student has different data. For example, the first student data as shown above, but the second student data name is not called Zhang San, want to change to Li Si.
The requirement is actually to reuse this component.
The solution is shown below:
Custom component incoming properties:
props can be used to transfer data between components (parent component passes data to child component's data)
Incoming Side: The incoming property is usually the parent component (), which is the following image.
Receive side: while writing props to receive parameters is usually a subcomponent. In fact, after receiving the props, it is equivalent to binding some properties of the props in its own data property.
In components that want to be reused, the data part of the field can be written as props. there are three ways to write this as shown in the following figure:
Three ways to write props (from simple to complex)
Summary:
-
The props property is actually a property in data. props can be used to transfer data between components (parent component passes data to child component's data)Data can be retrieved directly from vc, so naturally the fields in props can be retrieved as well. - But props' fields have higher priority than data's, which means that if data and props have the same name field, vue will render the value of props for us first. -Vue will render the props value for us first.The props field, once determined, cannot be tampered with. If you want to tamper with it, tamper with props using data.
[Note]: props are read-only. vue will warn you about changes to props. If you really want to modify them, use data to tamper with the props.Binding props in both directions with a v-model is a high-risk operation because it causes modifications to the props!
More examples: parent component utilizes v-for with props to dynamically create multiple child components
The parent component passes in the code:
<ul>
<MyItem v-for="(todoObj,index) in todos" :key="" :todo="todoObj"></MyItem>
</ul>
- 1
- 2
- 3
- 4
A todos is an array with a bunch of different objects in it. todoObj is each element of the array.
The todo is the custom property to be passed to the subcomponent, transmitting a single todoObj to the subcomponent at a time. Note the use of v-bind (😃 binding.
The subcomponent receives the code:
<script>
export default {<!-- -->
name:'MyItem',
props:['todo']
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Although data is not written, the todo in props can already be used according to the data attribute.
[Important] How can a son pass data to his father?
The answer is to pass in a function call. The father passes a function to the son, and then the son picks up the function with props, and when he does, he calls the function and passes the son's data into the function. This way the son's data is passed to the parent component.
Parent code:
<template>
<ul>
<son
// Pass a function to the son, who will call it, thus transferring data to the father.
:fatherFunc="myFunc" // Never add parentheses! Otherwise it will report an error
></Son>.
</ul>
</template>.
<script>
import Son from ". /";
export default {<! -- -->
components: {<!
components: {<! -- --> Son }, methods: {<!
methods: {<! -- -->
myFunc(id){<! -- -->
("Son data has been received!" +id) // output 123
}
}
};
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
Subcode:
<button @click="transToFather"> point me to pass the son's data to the father</button> //call the method
<script>
export default {<! ---->
name:'Son', //script> export default {<!
data() {<! -- -->
return {<! -- -->
sonId:123
}
},
props:['fatherFunc'],
methods: {<! -->
transToFather(){<! ---->
() // Call the function given by the father, passing in the son's id. This way the father receives the son's data
}
}
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
In addition to this way the child to the parent to pass data, you can also move to Chapter 8: 8, component customization events ($emit)
[Important] How to transfer data between brother components
Between brothers, they must have common parent components. For example, App, App must be the top-level parent component
So the transfer between brother components can be done by passing brother A to the father, who then passes to brother B
This is the original way of transferring. For more information about using props to pass from father to son, from son to father, and from brother to brother, see the Shan Silicon Valley video:
/video/BV1Zy4y1K7SH?p=72
5.4 mixin
The problem scenario that mixin needs to solve:
localized introduction of mixing
Start by writing the mix.js file:
The blend is then introduced in a component:
Global introduction of mixing
If you write it like below, as long as it's in the entry function, then all your vc's and vm's introduce that mix!
Summary:
5.5 Plug-ins (install)
Plugin application scenarios (similar to java's guide jar package)
Similar to importing jar packages in java, theimport ;
, citing powerful tools that others have already written!
For example, as previously mentioned:
- Filter - global directive - mixin - Add a method to the Vue prototype so that vm and vc share the method: (
= ()=>{alert("Hello")}
)
Create the plug-in as shown below:
Global reference to the plugin in the entry () (only the entry can write big Vue, aka vm):
Then any component vc can use the powerful features given to us in the plugin:
summarize
5.5 scoped CSS style scopes
scoped solves the pain point:
Two different components with renamed class attribute
The class selectors are also all the same, but in different colors.
If you introduce both components at the app at this point, it will trigger a style conflict!
Solution: Make style effective only for this component!
Add “scoped” attribute to limit CSS to this component only
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {<!-- -->
margin: 40px 0 0;
}
ul {<!-- -->
list-style-type: none;
padding: 0;
}
li {<!-- -->
display: inline-block;
margin: 0 10px;
}
a {<!-- -->
color: #42b983;
}
</style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
6. TODO List Cases (original version)
Demand:
All the points of the case have been learned before. Only the code location is given here:
Summary:
7、Browser local storage(localStorage,sessionStorage)
Introduction to the concept:
Search for: leather shoes without logging in; close the browser and restart it, it still has the record It means that the browser cached the data to the local hard disk:
View the site's local storage in your browser:
Pure JS implementation of the browser local storage function:
localStorage
The following api is a set of functions of localStorage, and there is a brother called sessionStorage, which has the same function.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>localStorage</title>
</head>
<body>
<h2>localStorage</h2>
<button onclick="saveData()">点我保存一个数据</button>
<button onclick="readData()">点我读取一个数据</button>
<button onclick="deleteData()">点我删除一个数据</button>
<button onclick="deleteAllData()">Tap me to clear a data</button>
<script type="text/javascript" >
let p = {<!-- -->name:'John Doe',age:18}
function saveData(){<!-- -->
('msg','hello!!!')
('msg2',666)
//Stored objects need to be stored with theJSONSerialize it.
('person',(p))
}
function readData(){<!-- -->
(('msg'))
(('msg2'))
const result = ('person')
((result))
// (('msg3'))
}
function deleteData(){<!-- -->
('msg2')
}
function deleteAllData(){<!-- -->
()
}
</script>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
Even if the whole browser is closed and restarted, localStorage is still there.
sessionStorage
The session here is different from the back-end session, which means a session. If sessionStorage is applied, it is only applied to one session. That is, once the browser is closed, sessionStorage is gone.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>sessionStorage</title>
</head>
<body>
<h2>sessionStorage</h2>
<button onclick="saveData()">Tap me to save a data</button>
<button onclick="readData()">Tap me to read a data</button>
<button onclick="deleteData()">Click me to delete a data</button>
<button onclick="deleteAllData()">Tap me to clear a data</button>
<script type="text/javascript" >
let p = {<!-- -->name:'John Doe',age:18}
function saveData(){<!-- -->
('msg','hello!!!')
('msg2',666)
('person',(p))
}
function readData(){<!-- -->
(('msg'))
(('msg2'))
const result = ('person')
((result))
// (('msg3'))
}
function deleteData(){<!-- -->
('msg2')
}
function deleteAllData(){<!-- -->
()
}
</script>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
Summary:
8, component customization event ($emit)
The parent component receives the data passed by the child component without props by binding custom events to the child component.
This method still can't do a direct pass between brothers. It can only be passed indirectly through a parent-child relationship
The underlying principle is that the parent component binds a function to the child component vc instance; the child component passes the
Think: tied to a subcomponent vc instance, isn't there another one you've learned before:
r
- 1
e
f
s
be born in the year of (one of the 12 animals)
suffix forming noun from adjective, corresponding -ness or -ity
?
(negative prefix for verbs)
stagger
。
envoy
expense or outlay
The refs attribute? That's right. Using the
The refs property? That's right. Using the refs attribute also enables this functionality.
Binding (several ways to write it):
Parent component binding:
If you're using a ref binding, you can trigger it with mounted:
mounted() {
this.
r
e
f
s
.
s
t
u
d
e
n
t
.
.
(‘atguigu’,) // Bind custom events
},
Subcomponents are triggered using this.$emit (which can be triggered using this because it's tied to this):
As shown below: the first parameter is the name of the custom event specified by the father, and the second to nth parameters are the formal parameters to be passed to the father. Variable parameter list:
Unbinding (this.$off)
If it's written that way:this.$off()
i.e. to unbind all custom events (nothing is passed to unbind them all)
native modifier (binds native tags, not custom tags)
Parent components can bind not only custom labels to child components, but also custom labels like the@click="xxx"
This native labeling
However, direct binding like the above will not work (it will be assumed that you have bound custom tags), and you must bind it this way at this point:
@="xxx"
summarize
This method still does not do a direct pass between brothers. It can only be passed indirectly through a parent-child relationship
The callback function for the event, written in the parent component!
Supplementary (Developer Tools Event View)
9、Global Event Bus
conceptual
Communication between arbitrary components!
It's not a new point of knowledge, all the knowledge used, it's all there. It is just a thought. As you can see in the picture below:
The X component in the image above, which doesn't do any work, is just for the components to use when passing events.
The X component acts as a coordinator of all components, and X must ensure global visibility.
Where should X be placed? The answer is on the vm. This ensures that all component instance objects (vc) are visible!
principle
Go to the top, build X:
Why do you want to go on the operation? Because the only way to get VM is to get on!!!!
Open any of the components and find that the X can be found:
At this point, the principle of explanation is complete! But the actual development is still not this binding, the next look at the actual operation:
How to register the event bus
Register the global event bus on:
Here.
b
- 1
u
s
,
as soon as
be
ahead
top
persuade
(used form a nominal expression)
x
。
economize
order
common
be all right
ground
ask
act as
bus, which is the previously mentioned x. The convention is called
bus, which is the previously mentioned x. Conventionally called bus (bus translates to bus in English)
//Introduce Vue
import Vue from 'vue'
//Import App
import App from '. /'
// Turn off production prompts for Vue
= false
//create vm
new Vue({<! ---->
el:'#app',
render: h => h(App),
// Register on the lifecycle function (hook)
beforeCreate(){<! ---->
// Install the global event bus, here this i.e. vm!
. $bus = this; //$bus is the vm. vm can call $emit, etc.
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
Transfer data using any component of the event bus:
First, the knowledge point: $on
Using the $on(eventName) event Using the
e
m
i
t
(
e
v
e
n
t
N
a
m
e
)
stir up sb's emotions
show (one's feeling)
affair
classifier for clothes, luggage, decorations; piece of work; a matter, an event
as if
resolute
classifier for objects with a handle
V
u
e
regard as
be all right
"one" radical in Chinese characters (Kangxi radical 1)
classifier for individual things or people, general, catch-all classifier
classifier for families or businesses e.g. shops, companies
law court
(
mutually
just at (a time or place)
sentence-final interrogative particle
"one" radical in Chinese characters (Kangxi radical 1)
classifier for individual things or people, general, catch-all classifier
surname Shan
sole
(used form a nominal expression)
c
o
m
p
o
n
e
n
t
s
)
,
women
trump card (in card games)
man
"one" radical in Chinese characters (Kangxi radical 1)
surname Zhi
exist
classifier for families or businesses e.g. shops, companies
Li (surname)
point at or to
group
(
emit(eventName) Trigger event If you think of Vue as a family (equivalent to a single component), the hostess has been assigning the family (
emit(eventName) triggers the event If you think of Vue as a family (equivalent to a single component), the mistress has been assigning (emit) the man to do things around the house, while the man has been listening (
o
n
)
(chess) move
women
scholar (old)
(used form a nominal expression)
point at or to
group
(
The lady's assignment (
The event message triggered by eventName in the Ms.'s assignment (emit), once the
e
m
i
t
affair
classifier for clothes, luggage, decorations; piece of work; a matter, an event
"one" radical in Chinese characters (Kangxi radical 1)
stir up sb's emotions
show (one's feeling)
,
Once the emit event is triggered, the
Once the emit event is triggered, on listens to the event dispatched by $emit, and the commands dispatched and the things to be done to execute the dispatched commands correspond to each other.
o
- 1
n
,
respond in singing
on, and
on, and emit is a pair, their formal parameter is also the same (are event name), one is listening to the other is triggered.
Look directly at the example:
The Student component and the School component are sibling components.
Student code:
<script>
export default {<!-- -->
name:'Student',
data() {<!-- -->
return {<!-- -->
name:'John Doe',
sex:'male',
}
},
methods: {<!-- -->
sendStudentName(){<!-- -->
this.$bus.$emit('hello',)
}
},
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
When sendStudentName is triggered, immediately use the event bus (
b
- 1
u
s
)
first (of multiple parts)
(used form a nominal expression)
bus)
The emit method on the (bus) triggers the event to be sent.
School Code:
(coll.) fail (a student)
e
- 1
m
i
t
(indicates passive-voice clauses)
stir up sb's emotions
show (one's feeling)
,
emit is triggered.
emit is triggered and on receives it immediately (triggering a callback)
due to
o
- 1
n
respond in singing
on and
on and off are a pair, get in the good habit of using $off to unbind before you get destroyed.
<script>
export default {<! -- -->
name:'School', props:['getSchoolName'], -->
props:['getSchoolName'], data() {<!
data() {<! ---->
return {<! -- -->
name:'ShangSilicon Valley',
address: 'Beijing', }
}
},
mounted() {<! ---->
this.$bus.$on('hello',data =>{<! -- -->
("This is the school component, I received data from my brother: "+data) // Output "Zhang San"
})
},
//Good habit: unbinding custom events once that vc has been killed.
// Thoughts: why not call destroy on top of student? Because you need to consider that multiple components are listening to school at the same time, which is a one-to-many relationship.
//$on and $off are a pair
beforeDestroy() {<! -->
this.$bus.$off("hello")
},
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
summarize
10、Message subscription and release
Would have been surprisingly simple after what came before, this chapter doesn't even have much to say...
and global event bus are similar technologies. Implementing inter-component communication
This is actually accomplished with the help of third-party libraries. Third-party libraries are all over the place, so use whichever one you want.
Here we have chosen to use pubsub-js (pubsubscribe).
Note that this can also be used with react, angular and other frameworks.
Install the library:
npm i pubsub-js
Use the library (there are only three commonly used methods: subscribe to subscribe, unsubscribe to unsubscribe, and publish to publish):
The Student component and the School component are sibling components.
Student code:
<script>
export default {<!-- -->
name:'Student',
data() {<!-- -->
return {<!-- -->
name:'John Doe',
sex:'male',
}
},
methods: {<!-- -->
sendStudentName(){<!-- -->
// this.$bus.$emit('hello',)
('hello',666)
}
},
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
When sendStudentName is triggered, the event send is triggered immediately.
School Code:
Get in the good habit of using unsubscribe to unbind before you get destroyed.
<script>
export default {<! -- -->
name:'School', props:['getSchoolName'], -->
props:['getSchoolName'], data() {<!
data() {<! ---->
return {<! -- -->
name:'ShangSilicon Valley',
address: 'Beijing', }
}
},
mounted() {<! ---->
// this.$bus.$on('hello',data =>{<! -- -->
// ("This is the school component, I received data from my brother: "+data)
// })
= ('hello',(msgName,msgData)=>{<! ---->
("Someone has posted" + msgData)
})
},
beforeDestroy() {<! ---->
// Unsubscribe
()
// this.$bus.$off("hello")
},
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
Summary:
11、$nextTick
The scenario is consistent with bypassing the rule chain:
You want to perform some operation on the new DOM after it has been rendered; but again, you have this operation encapsulated in the same function as modifying the dom. You now want to bypass the rule chain. Then there are two ways to do it:
- 1、 setTimeout
setTimeout(() => { // Operate on the new DOM }, 1000);
- 1
- 2
- 3
Delayed way to bypass the rule chain(of a computer) run - 2、Use $nextTick
this.$nextTick(function(){ this.$refs.inputTitle.focus() // perform operations on the new DOM, such as focusing })
- 1
- 2
- 3
- Both methods work, and the essence is really to bypass the chain of rules.
12. Transitions and animations
Scene:
Click the button to toggle the show/hide effect:
It's really Vue with CSS.
HTML Keywords:
<transition>
n. transition; transformation; change; alteration<transition-group>
CSS binding keywords:
xxx-enter-active xxx-leave-active
The full code is available at <style scoped> h1{<!-- --> background-color: orange; } /* Starting point of entry、The end of the line. */ .hello-enter,.hello-leave-to{<!-- --> transform: translateX(-100%); } .hello-enter-active,.hello-leave-active{<!-- --> transition: 0.5s linear; } /* entry point、Starting point of departure */ .hello-enter-to,.hello-leave{<!-- --> transform: translateX(0); } </style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
animate adj. having life; vitality; alive
It is a molded animation library that just needs to be introduced.
Official website:
First you need to install it and execute the command:
npm install
Use the sample code location: the above figure in the
The tutorial here is for vue
<transition>
tags to go along with this library.This way we don't have to write the css by hand, we can just get it ourselves from on-demand.
summarize
IV. Vue ajax
1. Prior knowledge and preparation
You must at least understand:
- Native ajax- promise- axios- cross domain concepts:
2, Vue in the basic use of axios
Send a get request using axios (assuming your vue front-end app is running on 8080 and the address you want to send the get request to is 5050):
<script> import axios from 'axios' export default {<! -- --> name: 'App', methods: {<! methods: {<! -- --> getStudents(){<! -- --> // Assuming your vue front-end app is running on 8080, the address you want to send get requests to is 5050 ('http://localhost:5000/students').then( response => {<! ----> ('The request was successful',) }, error => {<! -- --> ('The request failed',) } ) } } </script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
Cross-domain was found (violation of the same-origin policy):
Cross-domain specifies that three things must be consistent: protocol name, host name, and port number, or else the cross-domain!
Supplementary knowledge] ajax cross-domain issues
What is cross domain:
When a browser requests a resource from one web page on another domain, any difference in domain name, port, and protocol is a cross domain.
Cross-domain encountered: the request can be sent normally, but the browser refuses to receive the response.
Cross-domain restrictions:
- 1, Cannot read Cookie, LocalStorage and IndexedDB of non-homologous web pages - 2, Cannot touch DOM of non-homologous web pages - 3, Cannot send to non-homologous addressesSend AJAX request(can be sent, but the browser will reject the response)
Resolve cross-domain: - cors resolution (back-office resolution) The person who wrote the server gives you a couple of special response headers when they return the response. When the browser parses the special response headers, it will release the response. - jsonp solution: with the help of the src attribute inside the script tag, the introduction of external resources are not subject to the restrictions of the same source policy to realize. And it can only solve the cross-domain problem of get requests. - - - - - - - - - - - - - - - - - - - - - - -Configure a proxy server:
Building a proxy server with vue-cli
Method I (simple)
Look directly at the official website:
Once configured, then point the address you want to request, not directly to the original server, but directly to the proxy server:
(Still using the above as an example):
Method II:
The above way of configuring a proxy can only configure one proxy server, another more powerful way is described below:
Or go to the official website:
There are many more parameters that can be customized inside:
- The proxy prefix of the parameter: The role is simple, as shown below:
- Parameter: changeOrigin:false (default true) Controls whether the proxy server lies (change the port of your own proxy server, i.e., the host value in the request header) - Parameter: ws (default true) Supports or does not support webSocket
Summary:
Consolidated cases (mock requests)
Demand:
This comprehensive case simulation requests a github interface. However, for reasons that are well known, Github is not accessible in mainland China. So I used Node + express to build a simple server, and the case only needs to request my own server.
Server source code:
const express = require('express') const app = express() ((request,response,next)=>{<! ----> ('A request has been made to the Github server.'); // ('The request is coming from ',('Host'));; // ('Address of the request',)); next() }) ('/github',(request,response)=>{<! ----> let id = ; const users = [ {<! ---->imgurl:'/it/u=3117693326,3861562318&fm=253&fmt=auto&app=138&f=JPEG?w=359&h=239', name: "Daikichi"}, {<! {<! ---->imgurl:'/image_search/src=http:%2F%%2F50%2Fv2-c7875263af61123a7085ac188dcfef69_hd.jpg&refer=http:%2F%&app= 2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650173874&t= 3e72978d1e5fc306ac9cd3bc506e5a38',name: "Koji Tasho1"},. {<! ---->imgurl:'/image_search/src=http:%2F%%2F50%2Fv2-8b3b38fea6c9f9668c4118f04c059da5_hd.jpg&refer=http:%2F%&app= 2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650173874&t= cabec2f0ad269cc6ca4e3d3a0c65b2ae',name: "Sakata"},. {<! ---->imgurl:'/it/u=1908604312,998341899&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500', name: "bananagun"}, {<! {<! ---->imgurl:'/image_search/src=http:%2F%%2Fbfs%2Farticle%&refer=http:%2F%&app=2002&size=f9999,10000& ;amp;q=a80&n=0&g=0n&fmt=auto?sec=1650173992&t=251951e5eb80e1d2006de2f8b6b53564',name: "Bulgarian Demon King"},. ] (`The server has received the id from the client:${<! ---->id}, and has returned a bunch of user information`);); const resp = {<! ----> id: id, users: users users: users } ((resp)) }) (5000,(err)=>{<! ----> if(!err) ('GitHub server started successfully, requesting address: http://localhost:5000/github');; })
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
Code Location:
Final effect:
3、vue-resource
And axios similar technology. Only officially maintained by vue.
It is a plugin and is required for its use:
Installation:
npm i vue-resource
Use plug-ins:
You can find that his API is the same as axios and is also promise style. Just for information
4. slot slot
It's really just component tags applying other tags internally.
Simplest Slot
Parent component code:
Subcomponent code:
Slots can be marked
Named slots
Slots with names for multiple slots
It actually specifies the name attribute:
<template v-slot:xxxxx>
Add a template tag, which will not be displayed when finally parsed into html. And you can use the tag v-slot.
But you don't add the template tag, please use it normally
slot=xxx
I can't use the v-slot.Scope slots (
<template scope="xxx">
)Slot-scope is also possible, but written differently.
The scene is shown below:
The method is simple: add labels to the sub-slots. This way the data can be passed on to the user of the slot
How does the parent component receive it? As shown below:
summarize
Slots are actually a way for parent-child components to communicate with each other.
V. vuex
1. Basic concepts and application scenarios
- First of all it is a plugin. Use the
(Vuex)
Introduced- is a way of communicating between components and is suitable for any inter-component communication.
Usage Scenarios:
When multiple components depend on the same state (variables), or behavior from different components needs to change the same state (actually reads and writes from multiple different components), it is best to apply vuex!
2、[Interview]VuexWorking Principle
Interpretation of the chart below:
- store (actually the Vuex below): the father of Actions, Mutations, and States, the state transitions between the three of them (the api with the gray arrows) are provided by the store (, etc.)
- Actions: a plain Object type object, vc changes will first pass the value to action via (). then sent to Mutations via action via ().
Actions can also interact with the backend via ajax, which is the Backend API in the figure below, taking data through the backend interface, which is also assembled into the Action
If you don't call the Backend API, the VC can give the data directly to the Mutations, bypassing the Actions. i.e. Actions can be skipped!
- Mutations(n. Mutations, Changes): it is an object of type Object. It is responsible for the real processing, processing the modified data, and passing the processed data into State when the processing is finished
Vue's development tool, Devtools, monitors the data in Mutations.
- - State: also an object of type Object, vuex will render the data in it and give it back to the VC, updating the VC > If you don't call the Backend API, the VC can give the data directly to Mutations, bypassing Actions. i.e. Actions can be skipped
- Actions: a plain Object type object, vc changes will first pass the value to action via (). then sent to Mutations via action via ().
-
3、Build vuex environment
You're in a vue2 project, you can only install the vue3 version
You're in a vue3 project, you can only install the vue4 version
So install vue3 here:
npm i vuex@3
Introducing vuex:
import Vuex from 'vuex' (Vuex)
- 1
- 2
- 3
It is the agreed norm to create the store folder (or create the vuex folder) in the directory structure:
Sample content in store:
According to the working principle above, the store should contain at least actions,mutations,state, and then stuff these three things into the new store, and then finally expose the store:
// This file is used to create the core store in Vuex. import Vue from 'vue' //Introduce Vuex import Vuex from 'vuex' // Apply the Vuex plugin (Vuex) // Prepare actions - used to respond to the actions in the component const actions = {<! --> /* jia(context,value){ ('jia in actions was called') ('jia',value) }, jian(context,value){ ('jian in actions was called') ('JIAN',value) }, */ jiaOdd(context,value){<! --> ('jiaOdd in actions is called') if( % 2){<! -- --> ('JIA',value) } }, jiaWait(context,value){<! ----> ('jiaWait was called in actions') setTimeout(()=>{<! ----> ('JIA',value) },500) } } // Prepare mutations - for manipulating data (state) const mutations = {<! --> JIA(state,value){<! ----> ('JIA in mutations was called') += value }, JIAN(state,value){<! ----> ('JIAN in mutations was called') -= value } } // Prepare state - for storing data const state = {<! ---> sum:0 // current sum } // Create and expose the store export default new ({<! ----> --> actions, mutations actions, mutations, state, {< ----> actions, ----> state, }) })
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
The following snippet is: (vm entry)
Once the introduction is complete, you NEW vm to create a store configuration item:
//Import store import store from '. /store' //create vm new Vue({<! ----> el:'#app', render: h => h(App), store, {< beforeCreate() {<! ----> . $bus = this } })
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
4. Hands-on (calculation program) using vuex
Code Location:
Fully resolved in one figure:
Actually similar to the three-tier architecture of SpringBoot in Java.
- Controller layer: functions in subcomponent vc -Service layer: Action layer. This layer can be omitted, but the most important thing is that this layer can interact with the back-end API! (can be omitted when not interacting) - Dao layer: mutations layer - DataBase: state layer
Dispatch encapsulation:
It's actually the same as if we were wrapping a big pile of code, as shown below, which can be done in theservice layerDraw out code encapsulation:
5, Vuex developer tools to use
What it detects is actually Mutations data.
6. getters configuration items
A picture will tell you:
When the data in state is to be fine-tuned, it can be reprocessed using getters (which can also be implemented in other ways)
7、mapState、mapGetters、mapActions、mapMutations
Introducing:
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
[Theoretical Foundations] An ES6 Shorthand:
By writing it this way, obj has both a,b,x,y inside it
mapState、mapGetters
[Do not understand the above shorthand] mapState a graphical explanation (in fact, it is just a shorthand calculation property)
mapGetter (in fact, it is just a shortened getter, the writing style and syntax and mapState is identical, so do not do the demonstration)
Summary:
mapMutations、mapActions
- mapMutations actually generate corresponding methods with the help of mapMutations, which willAutomatically call commitTo contact mutations! - mapActions are actually methods generated with the help of mapActions.Automatically call dispatchGo contact actions!
A picture below will show you:
8, vuex modular (namespace), ajax request server
Scenario: you can't write all actions, mutations, states, getters, etc. all in one store. Normal projects, such as the people module, the goods module, etc., will be encapsulated into different js files.
The syntax support needed is the: namespace keyword, which defaults to false, and which you need to set to true in order for the mapping relationships to be automatically generated by things like mapState and so on, as mentioned earlier!
Ertu Case Analysis
-
Figure 1: Store modularization configuration, and the use of axios in the Actions layer to request data from external servers As shown in the following figure, the Vuex entry is split into several separate modules, and you only need to introduce the moduleSending a request to an external server using axios is also very simple, except that it's split into an Action layer to do it - Figure 2: How the VueComponent component uses the Vuex configuration in the above figure The following figure follows on from the previous one, and the variable names and interactions are the same in both cases.
Case Effect:
Case Code Location:
9. Summarizing modularity
VI. vue-router (routing)
1. Concepts
Take a router for example: a set of key-value correspondences is a route. Multiple routes are managed by a single router.
Routing: route; router: router
SPA Single Page Application (SPA) application concept:
- No matter how you click, the browser does not refresh/jump to another page (ajax), but the browser address bar changes. - Why does the browser address bar change? To make it easier for the user to copy the URL with its customizable tab. -Why does the browser address bar change?There is only one complete interface for the entire application - Clicking on the page navigation does not refresh the page, data exchange is done through ajax requests!
A normal monolithic system (SSM+thymeleaf) is very hard to do this kind of partial refresh to update the address bar synchronously. It's either all localized refresh or just return a view (all address bar with whole page refresh)!
As shown in the figure below:
Here we do it via Vue-router.
The key is the path and the value may be a function or component.
2. Installation\introduction\basic use
Only vue-router3, can be applied to vue2; vue-router4 can be applied in vue3
Here we install vue-router3:
npm i vue-router@3
Introduce vue-router: in the entry js:
import VueRouter from 'vue-router'
(VueRouter)
Demand introduction
Let's realize a scenario like the one below:
2.1 Entry JS and base introduction of router
2.2 router-link、router-view、active-class
Using routing to implement the above toggle tab to locally refresh and update the address bar requires the use of the
<router-link to="/xxx">
This tag, as shown below (the essence of which will be translated in the html page as<a>
(Labeling):The chart below works:
Configure active-class
As shown below, the html attribute active-class is configured so that whoever is selected, the value inside will be added to which class!
The logic of the above figure is: About is selected, then its class will eventually become class="list-group-item active"; Home is selected in the same way, and its class will be appended with the value of the active-class after it.
Configuring the replace attribute
2.3 Catalog structure, a few notes
- Notice that the above, in fact, doesn't use the previously familiar tagging method of loading components. Instead, it's loaded directly using the
<router-view>
to load the component. Therefore, it is necessary to use the<router-view>
to load the components.We call them routing components, and those that require explicit use of tags to come in, we call them general components. - Routing components are generally placed in the pages folder. Although they are .vue format files, they are more like individual pages. - Routing components that have been hidden by switching are by default subject to a destruction process. Remounting it when needed (which can be verified with beforeDestroy()) does destroy it -Each component has its own$route
attribute, which stores its own routing information - On each component there are global$router
, which is uniquely shared globally!
3. Nested routes (children)
Scenario: it's actually a nesting of routes, a route over a route
Illustration:
Note: You need to add / to write a first-level route, and you cannot add / to write a second-level route.
summarize
4、Route passing parameters of the query parameters
Each component has its own
$route
attribute, which stores its own routing informationReceive parameters: just store them in the
this.$
Center:What about passing in parameters? What about passing in a parameter using the
:to
When you look at the passing reference above, there are actually two ways to write it:
-
String writing: As we all know.Use: bind toThen the contents of the double quotes are used asJS Expressionsparsed. Then we nest template strings like ````````. Template strings use
${ }
to wrap the parameters. So the final string is live. -Object Writeup: As we all know.Use: bind toThen the contents of the double quotes are used asJS Expressionsparsed. So you can write the object directly.
5、Routing params parameters of parameter passing
The prior knowledge is the following 6. Named routes (name attribute)
Not only can ajax use ? to pass parameters, but also directly in the path.
For example, /student?id=1, which can also be passed like this: /student/id/1 This is called the params parameter.
Special note! When a route carries the params parameter, you must use the following 6. named route (name attribute) if you use the to object writing style!
6. Named routes (name attribute)
It's too simple! It's to simplify writing a long string of routes: /home/new/message/1 This kind of thing is simplified directly by writing name:
7. Routing props configuration
Remember the props you learned earlier? It can be applied in routing:
The picture below shows it all in one picture:
Summary:
8, programmatic route navigation ($router)
Previously, routing jumps had to be implemented with the help of
<router-link>
tag, which we know is effectively the equivalent of a<a>
Tags.So what if we want to bind a routing jump on a button button, then we can't use the
router-link
Up.Programmatic route navigation and
<router-link>
Labeled the same, it can alsoConfiguring the replace attributeProgrammatic route navigation,, in fact, writes the router-link configuration items to a custom function that operates with the help of a router (this.$router) that is shared globally by all components.
It is also possible to take one step forward and one step backward with the help of $router's other APIs, and jump at will:
<template> <div class="col-xs-offset-2 col-xs-8"> <div class="page-header"> <h2>Vue Router Demo</h2> <button @click="back">be back</button> <button @click="forward">advance</button> <button @click="test">advance3a pace</button> </div> </div> </template> <script> export default {<!-- --> name:'Banner', methods: {<!-- --> back(){<!-- --> this.$() // (this.$router) }, forward(){<!-- --> this.$() }, test(){<!-- --> this.$(3) } }, } </script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
9. Cache routing component (
<keep-alive>
Tags)Scene:
The reason for the above problem is actually very simple, as I said before, once you switch components, the previous component is directly destroyed, and then switch back to re-create a new component.
So caching the routing component is just a matter of keeping it mounted and not destroying it when it switches!
If you want to cache multiple routing components, write it this way (to be bound with v-bind):
<keep-alive :include="['News','Message']">
- 1
- 2
10. Two new lifecycle hooks (only in routing)
activated(), deactivated() when the route is activated/deactivated
As I said before, once you switch components, the previous component is directly destroyed, and switching back again creates a new component.
As talked about in Section 9, if you don't want this component to be destroyed, you can use a cache routing component.
But you still want actions and behaviors to be generated when the page switches, then you can use activated(), deactivated() to control the component when the route is activated/deactivated.
This way you don't destroy the routing component even if you cache it, then still switching will perform activation and deactivation.
Example:
<script> export default {<!-- --> name:'News', data() {<!-- --> return {<!-- --> opacity:1 } }, /* beforeDestroy() { ('NewsThe component is about to be destroyed.') clearInterval() }, */ /* mounted(){ = setInterval(() => { ('@') -= 0.01 if( <= 0) = 1 },16) }, */ activated() {<!-- --> ('NewsThe component is activated.') = setInterval(() => {<!-- --> ('@') -= 0.01 if( <= 0) = 1 },16) }, deactivated() {<!-- --> ('NewsComponent deactivation.') clearInterval() }, } </script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
11. Route guards
Role: Controls the permissions of the route!
For example, if you are not logged into Taobao, you can't click on the personal center. Even if you enter that route for the personal center (/myCenter) in the address bar, it will force you to jump to the login page.
11.1 Global Route Guard
Why is it global? Because it needs to be configured at the router entry () so that all your routes registered here will call the route guard function.
Global Front Route Guard: ()
Called when the route is initialized;
or before each route (route) is switched to, the router (router) calls this function for each route.
The forward route guard acts as an interceptor and does not release as long as next() is not called!
Global back routing guards: ()
Called during initialization and after every route switch. Not used much
Example: Read the browser's localStorage, if you find a set of key-value pairs 'school'='atguigu', then you can determine that the user is logged in, and allow the user to access the route.
Code Implementation:
Keywords in the image above:
- to: the end of the route
- - **meta (route meta information/route customization information): can hold some special customized data, logos, etc., but must be placed in mata, and the attribute name must be meta.** ### 11.2 Exclusive Route Guard (beforeEnter)
-
Exclusive route guards are only front, not rear
It's really just a matter of moving the global front-end route-guard code to where the routes are registered:
11.3 Intra-component Route Guard
Previously, route guards were configured inside the route entry (), and in-component route guards are, as the name suggests, configured inside the VueComponent
beforeRouteEnter() 、beforeRouteLeave()
The guards on the way out have NEXT and can decide to release or not.
12. Two modes of operation of the router (history, hash)
- hash mode The router's /#/ and the paths that follow it are called the path's hash value.It is characterized by the fact that it is not sent to the server with the server's request. That is, only the ones before # are sent to the server, not the ones after #. The default is hash mode, if you want to change it to history mode, as below (mode:'history'): - history mode will be sent to the server with the server's request No /#/, slightly less compatible.The understanding of poor compatibility can be explained in the following front-end project go-live process. It is very important here . The understanding of poor compatibility can be explained in the following front-end project go-live process. It is very important here . The understanding of poor compatibility can be explained in the following front-end project go-live process. It is very important here .
Front-end project go-live process
Essentially it's taking the entire project you've written and packaging it up. Packaging generates .html css, js files. Only this pure file format can be parsed by the browser. The .vue format is something that browsers simply don't recognize.
This process is a webpack knowledge point.
Execute the command :
npm run build
, will suffice.After packaging, a dist folder will be created, open the folder is html, css, js files.
The packaged stuff has to go to the server, for the deployment action.
Deployment here can be deployed in two ways:
- Combined deployment: static resources and the server in the same package (such as springboot jar package, nodejs + express composition of the mini-server can be) - Separate deployment: dist and the server code are packaged separately deployed
Here is a simple server demo deployment with nodejs+express: - Create a new folder:
mkdir vue_deploy
, and then go into that folder:cd vue_deploy
- Execution of orders:npm init
- Create a new js file as a server entry:touch server_test.js
- Server_test.js writes the code internally:
const express = require(‘express’) const app = express()
- 1
- 2
// Specify static resources exclusively, must
// Specify static resources exclusively, must
// Specify static resources exclusively, must
((__dirname+‘/static’))(‘/person’,(request,response)=>{
const resp = {
id: 123,
users: “users”
}
((resp))
})(5000,(err)=>{
if(!err) ('The server was started successfully, the request address is: http://localhost:5000/person').
})- Create a new folder static in the root directory (because the static resource directory specified above is /static) - Copy all the files in dist to static - [Optional].
npm i express
Install express - Execute the command:node server_test.js
Start the server - access:http://localhost:5000
, you can see your Vue front-end project directly!
One problem with this is that if you enable the router in history mode, it will report an error when it actually comes online and the server will request resources that don't exist!As you can see in the image above, if you are in history mode, then all of the boxes circled in the image below will be treated as a single server request, requesting server resources! But as we know, the box in the image above is nothing more than ourPure front-end routingIt's just that, by definition, it has nothing to do with the back-end. The backend shouldn't be requesting a resource from the server based on that string of links. The server doesn't have that resource either. So a predictable error is reported (as shown below):
The solution is actually very simple, change the working mode of the router to hash, then the problem is solved! hash only # before will be sent to the server, # after will not be!
What if I have to use history mode? It's possible. But that's a problem that needs to be thrown to the backend to solve.
The backend matches, by matching, which requests are purely front-end, and then doesn't respond to those requests sent to the backend. That's all.
- In the NodeJS server you can use the library: connect-history-api-fallback- There are also libraries for this in the backend written in Java. - - - - - - - - - - - - - - - - - - - - - - -Nginx was also born to solve this problem, and it can be configured to automatically help us distinguish between routes that need to be responded to by the back-end, and those that are purely front-end routes!
summarize
Vue UI component library
Vue Adaptation Component Library Recommendations
Component libraries are called component libraries because they must be component libraries for adapting componentized development. So Vue has component libraries adapted for Vue and React has component libraries adapted for React.
Since it is a component, it all needs to be used: (XXX)
All of the following are Vue adaptations:
Mobile:
- Vant /vant- Cube UI /cube-ui- Mint UI - NutUI Jingdong mobile Vue component library!
PC side: - Element UI - IView UI
Special recommendation: nail rake (tinper-bee)
It's going to be recommended again in my React notes!
/design-new/
tinper-bee
is a set of software based on(used form a nominal expression)expand one's financial resourcesComponent libraries, which are precipitated from rich enterprise-level middle and back-end application scenarios, provide consistency for the rapid development of complex applications.
UI
Solution.Full and on-demand introduction of components
Take Element UI for example: if you introduce all of it:
//Introduce ElementUI component library import ElementUI from 'element-ui'; //Import all ElementUI styles import 'element-ui/lib/theme-chalk/'; //Import all the styles from 'element-ui'; //Import all the styles from ElementUI. //apply ElementUI (ElementUI); //apply ElementUI
- 1
- 2
- 3
- 4
- 5
- 6
- 7
It will be found to be bloated:
So we need to introduce it on demand:
Sample:
= {<!-- --> presets: [ '@vue/cli-plugin-babel/preset', ["@babel/preset-env", {<!-- --> "modules": false }], ], plugins:[ [ "component", {<!-- --> "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ] }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
The introduction of on-demand in the
import Vue from 'vue'; import {<!-- --> Button, Select } from 'element-ui'; import App from './'; (, Button); (, Select); /* Or write * (Button) * (Select) */ new Vue({<!-- --> el: '#app', render: h => h(App) });
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
Just follow the guidelines on the official website