One, Vue basics
1.1. Overview
Author: especially the rain the river
Official website: https://cn.vuejs.org
Vue.js is a progressive framework for building user interfaces . Vue adopts a bottom-up incremental development design. Vue's core library only focuses on the view layer. It is not only easy to use, but also easy to integrate with third-party libraries or existing projects. On the other hand, when combined with single-file components and libraries supported by the Vue ecosystem, Vue is also fully capable of providing drivers for complex single-page applications. (SPA single page application, all displays are in one page)
Progressive: step by step, not that you have to use everything at once
Bottom-up design: It is a process and method of designing a program, which is to write a basic program segment first, and then gradually expand the scale, supplement and upgrade some functions. In fact, it is a process of constructing a program from the bottom up.
From a design perspective, Vue can cover all the things on this picture, but you don't need to use everything as soon as you get started. They are all optional. Declarative rendering and component systems are included in the core library of Vue , and routing, state management, and construction tools all have special solutions. These solutions are independent of each other, and we can choose other components on the basis of the core arbitrarily, not necessarily all integrated together.
1.2, declarative rendering and componentization
- Declarative rendering
The core of Vue.js is a system that allows the use of concise template syntax to declaratively render data into the DOM, for example:
<div id="app">
<!-- 渲染 -->
{
{ message }}
</div>
<script type='text/javascript'>
var app = new Vue({
el: '#app',
data: {
// 声明一下变量
message: 'Hello Vue!'
}
})
</script>
- Componentized application construction
Component system is another important concept of Vue (follow-up study), because it is an abstraction that allows us to use small, independent and usually reusable "small building blocks" to build large applications. Almost any type of application interface can be abstracted as a component tree.
1.3, development mode
Note: development mode ≠ design mode
The development model is the method or standard of a development project.
Three common development modes: MVC, MVP, MVVM
- MVC
The full name of MVC is Model View Controller, which is an abbreviation of model-view-controller, a model of software design, using a business logic (C), data (M), interface display ( V) Separate method to organize the code and gather business logic into one component. While improving and customizing the interface and user interaction, there is no need to rewrite the business logic.
- The user can send instructions (DOM events) to the View, and the View directly asks the Model to change the state.
- The user can also send instructions directly to the Controller (change the URL to trigger the hashChange event), which is then sent to the View by the Controller.
- Controller is very thin and only plays a role of routing, while View is very thick, and business logic is deployed in View.
advantage
Low coupling, high reusability, fast deployment, high maintainability, which is conducive to software engineering management
Disadvantage
Since the model and the view must be strictly separated, it brings great difficulties to the front-end program, and each operation needs to be thoroughly tested
- MVP
MVP is the abbreviation of Model-View-Presenter. MVP evolved from the classic pattern MVC. Their basic ideas are similar. Controller/Presenter is responsible for logical processing, Model provides data, and View is responsible for displaying:
- The communication between the various parts is two-way.
- View and Model are not connected, they are all passed through Presenter. You can use one Presenter for multiple views without changing the logic of the Presenter. This feature is very useful because the view changes more frequently than the model changes.
- View is very thin and does not deploy any business logic, called "Passive View" (Passive View), that is, there is no initiative, while Presenter is very thick, and all logic is deployed there.
Disadvantage
Since the rendering of the view is placed in the Presenter, the interaction between the view and the Presenter will be too frequent. Once the view needs to be changed, then the Presenter also needs to be changed.
- MVVM
- M: (model) ordinary javascript data object
- V: (view) front-end display page
- VM: (ViewModel) is used for two-way binding of data and pages. For our course, it is an instance of Vue
The MVVM model renamed Presenter to ViewModel, which is basically the same as the MVP model. The only difference is that it uses two-way binding (data-binding): View changes are automatically reflected in the ViewModel, and vice versa. In this mode, the page input changes the data, and the data change affects the display and rendering of the page data
Vue uses the MVVM responsive programming model to avoid direct manipulation of the DOM and reduce the complexity of DOM operations.
advantage
- Low coupling. Views can be independent of Model changes and modifications. A ViewModel can be bound to different Views. When the View changes, the Model can remain unchanged, and when the Model changes, the View can also remain unchanged.
- Reusability. You can put some view logic in a ViewModel and let many views reuse this view logic.
- Can be tested. The interface has always been difficult to test, but now the test can be written for the ViewModel.
2. Getting started with Vue
1. Comparison of traditional DOM and Vue implementation
Taking the output of "Hello World" as an example, the native JavaScript and jQuery codes of the traditional development model are as follows:
Use Vue.js to realize the output "Hello World" case:
step
- Define the label used to populate the data
- Introduce the vue.js library file (
学习测试使用开发版本,项目上线换成生产版本
)- Use vue syntax to achieve requirements
- Fill the data provided by vue into the label in "Step 1"
The code snippet is as follows:
<body>
<!-- 1. 定义用于填充数据的标签 -->
<div id="app">{
{msg}}</div>
</body>
<!-- 2. 引入vue.js库文件 -->
<script src="./js/vue.js"></script>
<script type="text/javascript">
// 3. 使用vue语法实现需求
var vue = new Vue({
// 4. 将vue提供的数据填充到“第1步”中的标签里
el: "#app",
data: {
msg: "Hello World",
},
});
</script>
Detailed analysis of Vue instance:
-
Vue parameter object properties
- el: The location where the element is mounted, the value can be a CSS selector or a DOM element
- data: model data, the value is an object
-
Interpolation expression
{ {msg}}
- Fill data into HTML tags
Understanding : Front-end rendering method
The front-end rendering methods are:
- Native JavaScript splicing strings (difficult to maintain)
- Use front-end template engine (easy to maintain, but lack of incident support)
- Use Vue's unique template syntax
- Interpolation expression
- instruction
- Event binding
- Property binding
- Style binding
- Branch loop structure
- …
2. Vue devtools tool installation
Install the Vue Devtools tool through the Google plug-in store in Chrome. This tool helps us to debug Vue data and must be installed. The address of the Vue tool in the Google Store is: https://chrome.google.com/webstore?utm_source=chrome-ntp-icon
Please note: to open the chrome application store, you need to access the Internet scientifically . As for how to access the Internet scientifically, please solve it yourself.
After installation, open Chrome 开发者工具(F12或Ctrl+Shift+I)
to use:
Supplement: What should I do if I can't solve the scientific Internet problem by myself, but I need to use Vue development tools?
If it really can’t solve the problem of scientific Internet access, Vue officially also provides the plug-in source code to allow us to compile/build the Google Chrom plug-in. The steps are as follows (the plug-in process is a bit more troublesome < do not require mastering how to build >, here is a good build for the students , Can be used directly).
- Clone warehouse
- Git warehouse address: https://github.com/vuejs/vue-devtools
- Install dependencies
- Construct
- Open the Chrome extension page
- Open developer mode
- Load the unzipped extension, select the shells-chrome directory
- Drag the generated
.crx
file into the Google browser扩展程序
interface - Add the Google policy template file in the Windows Policy Manager, and add the ID corresponding to the plug-in to
配置扩展程序白名单
.crx
And the.adm
file has been packaged and uploaded to the public cloud, you can click to visit 2url.cc/l3M5x1 to download
- Authorize the plug- in in the Google Chrome
扩展程序
management interfaceVue.js devtools
- Allow access to file URL
- Collect various errors
3. The principle of Vue two-way data binding
Core: Data Agent + Publish and Subscribe
When an ordinary JavaScript object is passed to the data option of a Vue instance, Vue will traverse all the properties of this object and use Object.defineProperty to convert all these properties to getter/setter (data hijacking/data mapping). Notify changes when properties are accessed and modified. Each component instance has a corresponding watcher instance object, which will record the property as a dependency during the component rendering process, and then when the setter of the dependency is called, it will notify the watcher to recalculate, so that its associated component can be updated .
Object.defineProperty(obj, prop, descriptor)
obj
The object whose attributes are to be defined.
prop
The name of the attribute to be defined or modified.
descriptor
To define options.
Sample code:
<body>
<div id="app">
<div id="msg"></div>
<input type="text" name="" id="" oninput="changeVal(this)" />
</div>
</body>
<script src="./js/vue.js"></script>
<script type="text/javascript">
// 1. 定义对象
var userInfo = {
name: "这个信息虽然用户看不到,但是Vue可以追踪到",
};
// 2. 数据劫持
var obj = {
};
Object.defineProperty(obj, "name", {
get() {
return userInfo.name;
},
set(data) {
userInfo.name = data;
document.getElementById("msg").innerHTML = data;
return true;
},
});
// 3. 实时渲染
document.getElementById("msg").innerHTML = obj.name;
// 4. 发布订阅
function changeVal(eleObj) {
let value = eleObj.value;
obj.name = value;
return true;
}
</script>
4. Vue template syntax
4.1, interpolation expression
**Interpolation expression:** is a way to bind data in HTML templates provided by the vue framework. The usage {
{变量名}}
method binds the data variables in the data in the Vue instance, and the bound data will be displayed in the view in real time. come out.
The writing method of interpolation expression supports the use of:
- variable name
- Part of JavaScript expression
- Note: The
{ { }}
enclosed area is the js syntax area, in which part of the js syntax can be written. Cannot write var a = 10; branch statement; loop statement
- Note: The
- Ternary operator
- Method call (method must be declared first)
- …
<body>
<div id="app">
<!-- 直接使用变量名 -->
<h5>{
{name}}</h5>
<!-- 运算 -->
<h5>{
{name + '--好的'}}</h5>
<h5>{
{ 1 + 1 }}</h5>
<!-- 使用函数 -->
<h5>{
{title.substr(0,6)}}</h5>
<!-- 三目运算 -->
<h5>{
{ age > 18 ? '成年' : '未成年'}}</h5>
</div>
</body>
<script src="./js/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
title: "我是一个标题,你们看到没有",
name: "tianqin",
age: 21,
},
});
</script>
4.2. Instructions
Question 1: What is an instruction?
- The essence of the instruction is the Vue custom attribute in the label
- The command format starts with "v-", for example: v-cloak, v-text, v-html, etc.
For details, please refer to the instructions on the official website: https://cn.vuejs.org/v2/api/#%E6%8C%87%E4%BB%A4
Question 2: What is the function of the instruction?
When the value of the expression changes, the collateral effects produced by it will act on the DOM responsively. (Simplified operation)
Small test : v-text command and v-html command [equivalent to innertHTML and innerText]
Official website
v-text:https://cn.vuejs.org/v2/api/#v-text
v-html:https://cn.vuejs.org/v2/api/#v-html
Friendly reminder: Use v-html as little as possible or not, because it may cause XSS attacks.
<body>
<div id="app">
<!-- 插值表达式形式 -->
<div>{
{str1}}</div>
<!-- 插值表达式此时与v-text是等效的 -->
<div v-text='str2'></div>
<div v-html='str1'></div>
</div>
</body>
<script src="./js/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
str1: 'hello tianqin',
str2: '<a href="http://www.baidu.com">百度</a>'
}
})
</script>