1. KnowVue.js
1.1 Why LearnVue
From a practical point of view, you can find a satisfactory front-end job if you learn Vue well, but it is very difficult to find a satisfactory front-end job if you don’t master Vue (it should be added that in addition to Vue, many jobs now require “small programs”).
1.2 Vue
The characteristics of
Vue is a progressive JavaScript framework for building user interfaces:
- Full name is
Vue.js
或Vuejs
; -
What is a progressive framework?
- An incremental framework means that we can introduce and use it bit by bit in a project
Vue
, and not necessarily all of themVue
To develop the entire project. You can choose to use it (or not)Vue
You can also use it only in a module of the projectVue
.
- An incremental framework means that we can introduce and use it bit by bit in a project
1.3 Vue
和 React
And so on
The three most popular front-end frameworks are Vue, React and Angular.
Angular
: the entry threshold is high, and the domestic market share is low. But there is no denying that it is a very excellent framework in itself, and a lot of its design ideas are associated withNode
The frameworknest.js
They’re similar, and they’re basically all of themTypeScript
Development.React
: The market share is high both at home and abroad. Being a front-end engineer is also a framework that must be learned. Big companies and big projects were also more likely to use them in the pastReact
Development, because relatively speakingReact
Maybe more flexible, a little bitVue2
Scenes that might not be possible to doReact
Can do (of course, nowVue
从2
Version upgrade to3
After the version, there isComposition API
, is also very flexible).Vue
: Highest market share in the domestic market, almost all front-end positions will be rightVue
There are requirements.
1.3.1 Framework data comparison
1.3.1.1 Google
index
1.3.1.2 Baidu Index
1.3.1.3 npm
downloads
1.3.1.4 GitHub
1.3.2 Who is the best front-end framework
I’m not going to draw a conclusion here because there’s no point arguing about it, just like people arguing about who is the best language in the world.
But let’s look at it from a realistic perspective. Which language is more likely to get a job (and which one has more market share)?
- Looking for back-end jobs: Preferred
Java
, followed byGo
Again, isNode
(JavaScript
), probably not recommendedPHP
,C#
; - Looking for front-end jobs: Preferred
JavaScript
(TypeScript
), followed byFlutter
Again, isAndroid
(Java
,Kotlin
),iOS
(OC
,Swift
); - Other directions: algorithm engineer, game development, artificial intelligence, etc.
So, in terms of the front end, after learning HTML, CSS, JavaScript, which framework is more likely to find a job?
- If you are looking for a job abroad, it is recommended first
React
, followed byVue
和Angular
And is not recommendedjQuery
A; - If you are looking for a job in China, it is recommended and necessary to study
Vue
, followed byReact
Again, isAngular
And is not recommendedjQuery
.
1.4 learningVue2
orVue3
- For having mastered
Vue2
For the students, direct learningVue3
In the relevant content can; - For those who have not studied
Vue2
Students, direct learningVue3
Will do.
The Programmer: Vue3 is compatible with 2.x. Developers who want to learn Vue often have to decide whether to start with Vue2 or go straight to Vue3. What advice do you have?
You Yuxi (Vue Author) : Just learn Vue 3, the basic concepts are exactly the same.
1.5 Need to learn nowVue3
吗
On September 18, 2020, the much-anticipated version of VUE3 was finally released, named “One Piece”.
- It brings many new features: smaller size, better performance, better API design, better TypeScript integration;
- in
Vue3
When we first launched, a lot of people were excited to try itVue3
All kinds of new features, we useVue3
Write aboutdemo
There is no problem with practice, but it is really used in real business projectsVue3
There is a relative process; - including
Vue3
More stability and more communityVue3
Support and improvement of related plugins and component libraries (because it takes time for the tools, peripheries and libraries in the ecosystem to be compatible with each other,Vue3
Some of the new uses also take time to settle).
So now is learningVue3
What about the time?
- The answer is yes;
- First of all,
Vue3
After a series of updates and maintenance, it has been stabilized, and Yuyu Creek beforeVueConf China 2021
It was also announced that it would beQ2 of this year (2021)willVue3
As the default version (now the time is7
月10
No.,npm
It is not installed by defaultVue3
, and the document does not yet have a default pointingv3
Documents). - After a period of precipitation, the community has become more complete, including
Ant Design Vue
,Element Plus
Both are provided onVue3
So many companies are now using it for new projectsVue3
To develop it. - And in the interview, you’ll be asked
Vue3
,Vite2
Tool-related issues.
1.6 Vue3
The changes brought about
1.6.1 source
-
The source code is managed in the form of monorepo
mono
: a single;repo
:repository
(warehouse);- The idea is to store code for many projects in the same repository;
- This can make the multiple packages themselves independent of each other, can have their own functional logic, unit tests, etc., at the same time, but also in the same warehouse, convenient management;
- And the module is more clearly divided, maintainability and expansibility are stronger.
-
The source code was rewritten using TypeScript
- in
Vue2.x
When,Vue
useFlow
Type detection; - Now the
Vue3.x
,Vue
The source code is all usedTypeScript
Do refactoring, andVue
Itself toTypeScript
Support is also better.
- in
1.6.2 performance
-
Proxy is used for data hijacking
- in
Vue2.x
The time,Vue2
Is the use ofObject.defineProperty
To hijack the datagetter
和setter
Methods; - One drawback of this approach has always been the inability to hijack and listen when adding or deleting properties to an object.
- So in the
Vue2.x
Had to offer something specialAPI
, such as$set
,$delete
, in fact, some of themhack
Methods added for developers to learn newAPI
The cost; - And in the
Vue3.x
To start,Vue
useProxy
To achieve data hijacking, theAPI
And we’ll talk about the use of this and the principle of it;
- in
-
Removed some unnecessary APIs
- Removed on the instance
$on
,$off
和$once
; - Removed some features:
filters
(filter),inline template attribute
(inline template properties), etc.;
- Removed on the instance
-
Compiler optimizations
- generate
Block Tree
; Slot
Compiler optimization;diff
Algorithm optimization;
- generate
1.6.3 newAPI
-
From the Options API to the Composition API
- in
Vue2.x
By the time we get throughOptions API
To describe the component object; Options API
includingprops
,data
,computed
,watch
, life cycle events,methods
Etc.;-
A big problem with the Options API is that multiple logics may be in different places:
- Such as
created
Will be used inmethods
To modify one of the methods indata
In the data, code cohesion is very poor;
- Such as
- while
Composition API
You can put related code in the same place for processing, rather than having to spread it across multiple areasOptions
In, also need not again in multipleOptions
Between looking for;
- in
-
Hooks functions increase the reusability of code
- in
Vue2.x
When we usually go throughmixins
Sharing logic between multiple components; - But there is a big drawback
mixins
It’s also made up of a bunch ofOptions
Composed of, multiplemixins
There will be naming conflicts; - the
Vue3.x
We can go throughHook
Functions extract bits of independent logic, and they can also be reactive; - Specific benefits will be explained in the following exercises (including principles);
- in
2. Vue
The installation of
Once you know Vue briefly, how do you use it?
First of all, it’s important to know that Vue is essentially a JavaScript library. We don’t need to think of it as very complicated at first, just think of it as a library that has already helped us encapsulate and that we can introduce and use in our projects.
Before you can use Vue, you need to install Vue. There are four ways to install the JavaScript library:
- Pass through the page
CDN
The way to introduce; - download
Vue
的JavaScript
After the file is manually introduced in the page; - through
npm
Package management tool installation (speakWebapck
I’ll talk about it later. - Installed directly
Vue CLI
To installVue CLI
When the installationVue
(finishedWebpack
We’ll talk about scaffolding later, we’ll talk about scaffolding laterVue CLI
Create the project and use itVue
);
2.1 Mode 1CDN
The introduction of
-
What is a CDN? CDN (Content Delivery Network or Content Distribution Network, abbreviated as CDN)
- It refers to the use of the server closest to each user through interconnected network systems;
- Faster and more reliable delivery of music, pictures, videos, applications, and other files to users;
- To provide high performance, scalability and low cost network content delivery to users.
-
Commonly used CDN servers can be divided into two types:
- Their own
CDN
Server: Need to buy your ownCDN
Server, Huawei, Ali, Tencent, Amazon, Google and other platforms can be purchasedCDN
The server; - Open source
CDN
Server: the international use is moreunpkg
,JSDelivr
,cdnjs
;
- Their own
- through
CDN
The introduction ofVue
The latest version of:
<script src="https://unpkg.com/vue@next"></script>
If you visit the CDN address https://unpkg.com/vue@next in your browser, you can also see the uncompressed source code after Vue is packaged (uncompressed code is recommended during development, so you can see more details) :
As you can see, the top of the file defines a global variable Vue (which is actually an object), so we’ll use the global variable Vue next.
Hello Vue
Implementation of the case:
<! -- 4. The element used to mount the app object (usually div and set the id to app, but other elements and selectors can also be used) --> <div id="app"></div> <! -- 1. CDN Vue -- --> <script SRC ="https://unpkg.com/vue@next"></script> <script> const obj = {// 3. Template: '<h2>Hello Vue</h2>'}; <h2>Hello Vue</h2>'}; // const app = vue. createApp(obj); // const app = vue. createApp(obj); // mount the app object on the HTML element with the id of app (that is, tell the app object where to display it) // Instead of manually fetching the target element through the document.querySelector method, mount the app object on the HTML element with the id of app (that is, tell the app object where to display it). All we need to do is pass in the DOM string of the selector we want to match. // Because Vue internally uses this string to help us find the target element using the document.querySelector (source code: // packages/runtime-dom/src/index.ts -> createApp -> app.mount -> // normalizeContainer(containerOrSelector) -> if (isString(container)) -> document.querySelector(container)) app.mount('#app'); </script>
Summarize the five steps of using VUE in the above case:
- The introduction of
Vue
; - Create an object that contains the template.
- By global variables
Vue
callcreateApp
Methods (functions within an object are called methods) and pass in the object; - The returned object is called
mount
Method mounts itself on an element; - The template content is displayed on the page;
2.2 Mode 2. Introducing after downloading
Download the VUE source code, you can directly open the CDN link:
- Open the link (https://unpkg.com/vue@next) and copy all the code in it.
- Create a new file, such as
vue.js
Paste the copied code into the file.
Next, you can import the new file you just created with the script tag (for example, in “import locally. HTML”) :
<script src="./js/vue.js"></script>
Hello, Vue3
Implementation of the case:
<div id="app"></div> <script src="./js/vue.js"></script> <script> Vue.createApp({ template: '<h2> hello, Vue3</h2>'}).mount('#app'); </script>
3. Counter case
Let’s implement a counter example:
- Click on the
+ 1
Button, the page content will display the number+ 1
; - Click on the
- 1
Button, the page content will display the number- 1
;
There are a number of ways to do this, but we chose to do it in a native and Vue way, and compare the differences.
3.1 Native Implementation
<h2 class="counter"></h2> <button class="increment">+1</button> <button class="decrement">-1</button> <script> // 1. Gets the element that shows the current count and the two button elements const counterEl = document.querySelector('.counter'); const incrementBtnEl = document.querySelector('.increment'); const decrementBtnEl = document.querySelector('.decrement'); // 2. Define a variable to record the current count let counter = 0; // 3. Assign the initial value counterel. innerHTML = counter to the content of the element that displays the current count; / / 4. For the button to add a click event to monitor incrementBtnEl. AddEventListener (' click '() = > {counter++; counterEl.innerHTML = counter; }); decrementBtnEl.addEventListener('click', () => { counter--; counterEl.innerHTML = counter; }); </script>
3.2 Vue
implementation
<div id="app"></div> <! Vue --> <script SRC ="./js/vue.js"></script> <script> vue.createApp ({// This is not the case, but it is not the case) This allows you to preserve newlines and define strings across lines. // The following template contains a div, which is required by Vue2. In Vue3, you can remove the div. // Vue3's template outer element (div) can be left unwrapped (Vue2 must be wrapped with a root element, otherwise it will report an error: // Component template should contain exactly one root element. If you are using v-if on multiple // elements, Use v-else-if to chain them instead.) // You can use the "Mustache" syntax (double curly braces) to return properties in an object using the following data function properties; // A template can bind a click event to a property in the methods object below by binding it to the @Click event. template: ` <div> <h2>{{ message }}</h2> <h2>{{ counter }}</h2> <button @click="increment">+1</button> <button @click=" Decrement ">-1</button> </div> ', // CreateApp function passes in an object. Objects can have multiple attributes, and // Vue specifies that there can be data attributes as well. // The data attribute in Vue3 must be a function that returns an object. It is not allowed to pass the object directly. Datafn. call is not a function (data() {return {data() {return (); // They are all added to the Vue reactive system, so they are all reactive; // Both can use message: 'Hello World', counter: 0} in the template; }, // You can also have the methods attribute // Methods attribute for an object that defines various methods. Methods: {// Define the method for the "add one" operation (the syntax used to define methods in objects before ES6) increment: Function () {console.log(' Click +1'); // methods can be used to retrieve data from data (essentially, Proxy) this.counter++; }, // Method for defining a "Minus One" operation (syntax sugar for defining methods in ES6 objects) Decrement () {console.log(' Click -1'); this.counter--; } } }).mount('#app'); </script>
We can also do a little extraction of the above code (detailed in Section 4.1.1 of Template extraction) by modifying it as follows:
<div id="app"></div> <template id="my-app"> <h2>{{ message }}</h2> <h2>{{ counter }}</h2> <button @click="increment">+1</button> <button @click="decrement">-1</button> </template> <script src="./js/vue.js"></script> <script> const App = { template: '#my-app', data() { return { message: 'Hello World', counter: 0 }; }, methods: {increment: function() {console.log(' Click +1'); this.counter++; }, Decrement () {console.log(' Click -1'); this.counter--; }}}; Vue.createApp(App).mount('#app'); </script>
3.3 Imperative and declarative
As we’ll see, the patterns and characteristics of native development and Vue development are quite different, and there are actually two different programming paradigms involved:
- Imperative and declarative programming;
- Imperative programming focuses on how to do; Declarative programming focuses on what to do, and how to do the process is left to the framework (the machine).
How do we do that in the native implementation?
- Each time we do something, we need to write a piece of code in JavaScript to give the browser an instruction;
- This process of writing code is called imperative programming;
- In the early primitive
JavaScript
和jQuery
In development, we all write code in this imperative way;
How do we do this in the implementation of VUE?
- We will be in
createApp
The required content is declared in the incoming object: template (template
), data (data
), methods (methods
), the rest of the specific operation byVue
Help us finish; - The process of writing code in this way is called declarative programming;
- At present
Vue
,React
,Angular
Programming mode, are this declarative.
3.4 MVVM
model
-
MVC and MVVM are both software architectures:
MVC
是Model-View-Controller
An abbreviation for an architectural pattern for a framework that has been widely used in the past, such asiOS
And the front;MVVM
是Model-View-ViewModel
Is a very popular architecture pattern at present;
-
Typically, we also refer to VUE as an MVVM framework
Vue
The website actually says: “Although not fully followedMVVM
Model, butVue
The design was also inspired by it.”
The previous code that implemented the counter natively can be divided (though not very clearly) according to the MVC software architecture:
The previous code for Vue to implement the counter was written in accordance with the software architecture pattern of MVVM:
To sum up, the native implementation of the counter can be regarded as an imperative programming of the MVC architectural pattern, and the VUE implementation of the counter can be regarded as a declarative programming of the MVVM architectural pattern.
4. template
,data
,methods
Properties,
When we use CreateApp, we pass in an object. Let’s take a closer look at what the properties we passed in represent.
4.1 template
attribute
The template property represents the template information that Vue needs to help us render.
-
So far we can see that it has a lot of HTML tags in it, which will replace the innerHTML of the element (in our case, div with id app) that we are mounting to;
- Corresponding code in the source code:
packages/runtime-dom/src/index.ts
->createApp
->app.mount
->container.innerHTML = ''
.Vue
Will clear the contents before mounting;
- Corresponding code in the source code:
- There are some in the templateStrange Grammar, such as
{{}}
,@click
These are allTemplate-specific syntaxWe’ll come back to that;
But the way this template is written is a little awkward, and the IDE probably doesn’t have any hints that hinder the efficiency of our programming.
4.1.1 template
writing
The good news is that Vue gives us two other ways to write templates:
- Way one: use
script
Tag, and mark its type asx-template
To set upid
;
<script type="x-template" id="my-app">
<div>
<h2>{{ message }}</h2>
<h2>{{ counter }}</h2>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
</script>
-
The second option is to use any tag (usually the template tag, because it won’t be rendered by the browser) and set the id.
HTML
Content Template (<template>
The) element is a type used for savingHTML
This will not be rendered immediately after the page has loaded, but will be used later at runtimeJavaScript
The period may be instantiated.1
<template id="my-app">
<div>
<h2>{{ message }}</h2>
<h2>{{ counter }}</h2>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
</template>
-
At this point, in the object passed to the createApp function, we need to pass in a template that starts with #
- If the string is
#
Start, then it will be used asquerySelector
, and uses a matching elementinnerHTML
As a template string.
- If the string is
Method a complete code:
<div id="app"></div>
<script type="x-template" id="my-app">
<div>
<h2>{{ message }}</h2>
<h2>{{ counter }}</h2>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
</script>
<script src="./js/vue.js"></script>
<script>
Vue.createApp({
template: '#my-app',
data() {
return {
message: 'Hello World',
counter: 0
};
},
methods: {
increment: function () {
this.counter++;
},
decrement() {
this.counter--;
}
}
}).mount('#app');
</script>
Method two complete code:
<div id="app"></div>
<template id="my-app">
<div>
<h2>{{ message }}</h2>
<h2>{{ counter }}</h2>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
</template>
<script src="./js/vue.js"></script>
<script>
Vue.createApp({
template: '#my-app',
data() {
return {
message: 'Hello World',
counter: 0
};
},
methods: {
increment: function () {
this.counter++;
},
decrement() {
this.counter--;
}
}
}).mount('#app');
</script>
In development, it is recommended to write the template as
because of the code hints and code highlighting.
4.2 data
attribute
-
The data property needs to be passed a function, and that function needs to return an object:
- in
Vue2.x
You can also pass in an object (justVue
For instance, if it is componentdata
, then only acceptfunction
); - in
Vue3.x
You must pass in a function or it will report an error directly in the browser.
- in
-
Objects returned from data are hijacked by Vue’s responsive system, and subsequent access or modification to the object is handled in the hijacking;
- So here we are
template
Through the{{ counter }}
accesscounter
, you can get data from the object; - So let’s modify
counter
The value of the,template
In the{{ counter }}
It can also change;
- So here we are
- The specific principle of this response type, we will have a special space to explain later.
4.3 methods
attribute
-
The methods property is an object in which we typically define a number of methods:
- These methods can be bound to the Template template;
- In these methods, we canuse
this
The keywordTo access directly todata
Properties of the object returned in the
-
For experienced comrades, here is the following description in the official document 2:
- Consider two questions:
- Why can’t you use the arrow function? (Is the explanation given in the official document really understood?)
- What exactly does this point to without using the arrow function? (Can be used as an interview question)
4.4 Other attributes
Of course, there are many other properties in the object passed by createApp(), which we’ll cover later:
- Such as
props
,emits
,setup
,computed
,watch
And so on; - It also includes a lot of lifecycle functions;
Don’t worry, we’ll learn them one by one.
5. Vue
Source download, debugging, reading
-
Some of you may be wondering, didn’t you download the Vue source code in Section 2 above? Why do you want to download again?
- Because I downloaded it earlier
Vue
The source code is already packaged, and all the code is in one file, which looks very inconvenient.
- Because I downloaded it earlier
-
Some people may also ask that the Vue source code downloaded through the CDN in Section 2 contains not only ES5 code, but also ES6 code.
- That’s because it actually ends up passing when the project is packaged
babel
After the tool is set up, the code is packaged once (twice packaged, with compression and other processing), so it still exists for the time beingES6
The code should be fine.
- That’s because it actually ends up passing when the project is packaged
In the case of the Vue source code downloaded from the CDN in Section 2, we may read a function in it, but we will not read the packaged source code bit by bit. So what should we do? Here’s what we’ll do:
- Open the
GitHub
Website, type in the search box at the top leftvue-next
(i.e.Vue3
Version) to search; - Click in the search results
vuejs/vue-next
(As we can see, it is usedTypeScript
Write); -
After entering the vuejs/vue-next repository, there are two ways to download:
-
Git clone method (recommended) : Click the Code button, click the copy button directly after the URL link below to copy the URL, and then download the source Code as git clone method (why choose this method? This is because Git relies on Git to do some validation when it runs its dev. If you choose Download Zip and there is no git (a. Git folder is missing), your code may not work.
- Open the terminal (
Windows
On iscmd
Or useGit Bash
); - through
cd
Command into the directory where you want to store the source code for download later; - perform
Git clone the URL you just copied
Command, download the source code;
- Open the terminal (
Download ZIP
Method: Clickmaster
Pull down the button, clickTags
Tab, select the latest stable version to download (we generally do not downloadBranches
Under themaster
Main branch or otherdev
Branches (will eventually merge tomaster
In the main branch) because they are likely to be unstable code under development; whileTags
Under thexxx-beta.x
Is a beta version and is not stable enough), we will choose herev3.1.4
Version to download:
-
If you Download the source code using Download Zip and want it to run, you can do this:
- First unpack the downloaded source code compression package, with
Visual Studio Code
Open the unzipped folder (Vue - next - 3.1.4
); -
Open the terminal in Visual Studio Code, enter the yarn install command, and execute it;
- It needs to have been installed on your computer before
node
And usenode
To install ayarn
If not, you need to download it firstnode
(advice tonode
Download the “Long Term Support Edition” (LTS
) because relative to the “current release” (Current
), the “long-term support version” will be a little more stable); - After downloading and installing
node
After that, there will benpm
This tool, can be executed from the command line terminalnpm install yarn -g
Command, and then you have it on your computeryarn
This is a tool; - because
Vue
The source code is usedyarn
To manage the (source directory can be seenyarn.lock
File), so we need to executeyarn install
Command to installVue
Source required dependencies.
- It needs to have been installed on your computer before
- perform
git init
Command to change the current folder (Vue - next - 3.1.4
) to an emptyGit
Warehouse; - perform
git add .
The command adds all files in the current directory to the staging area; - perform
git commit -m "fix(install): install dependences"
Command to commit staging area contents to a local repository; - perform
yarn dev
(will essentially execute the current folderpackage.json
In the filescripts
In thedev
Script corresponding command), it will put the current folder under thepackages
All files in the folder (areVue
Source code), the packaged code will be placedpackages/vue/dist/vue.global.js
File (the file is actually uploaded toCDN
In the file above); - With this packaged source code file, we can go to
packages/vue/examples
Directory, create a new directory (e.gcoderzhj
) and create a new one in that directoryhtml
File (e.g.,demo.html
), and then you can use the packaged source file by introducing it in that fileVue
Write some code and put it inVue
The project is running:
If you download the source Code through git clone, you can open the vue-next folder under the location of the source Code directly with Visual Studio Code without decompressing it. If you want to switch to another version (such as the latest stable version v3.1.4), you can first run the git tag command at the terminal to check which tags are packaged. Switch to version 3.1.4 via Git Checkout v3.1.4 (if not, master by default), and then yarn install and execute yarn dev (or NPM dev) directly.
So what’s the use of running? You can use debugger in the script tag to debug:
For example, if we want to see what createApp does, we can go from F10 to vue. createApp and then F11 to the createApp function:
However, we will notice that we are debugging in a large file called vue.global.js, which means that all the source code is put together, which looks very inconvenient. Is there a way to jump to a specific source code file when debugging? Yes, we can modify the dev script corresponding to the script in the package.json file in the project directory and add — sourceMap at the end of the command:
Then re-execute the yarn dev and repackage the project and run it (the dist directory will have a vue.global.js.map file, which is the sourceMap file for debugging purposes). Each line of code during debugging can now be mapped to its specific file, so we can match the mapped file to the Packages folder in the project:
Write in the last
If there are any mistakes in this article, please correct them in the comments section.
- The
<template>
HTML element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript. — MDN ↩ - See https://v3.cn.vuejs.org/api/o… ↩