Front-end development learning [Vue]-Part 1

1 Overview

1 Introduction

Vue (pronounced /vjuː/, like view) is a progressive JavaScript framework for building user interfaces. It is built on standard HTML, CSS, and JavaScript, and provides a set of declarative, componentized programming models to help you develop user interfaces efficiently.

  • Build the user interface: turn the data into a user interface in some way
  • Progressive: Vue can be applied layer by layer from bottom to top. Simple applications only need a lightweight and compact core library, and complex applications can introduce various Vue plug-ins
  • You Yuxi Development

2. Features

  • Follow the MVVM pattern
  • Simple coding, small size, high operating efficiency, suitable for mobile/PC development
  • It only focuses on the UI itself, and can introduce other third-party library development projects
  • Adopt component mode to improve code reuse rate and make code easier to maintain
  • Declarative coding, so that coders do not need to directly manipulate the DOM, improving development efficiency
  • Use virtual DOM and Diff algorithm to reuse DOM nodes as much as possible

3.Diff algorithm

Real DOM :
The process of browser rendering mainly includes the following five steps:

  • The browser gets the HTML document and parses the DOM tree
  • Parsing CSS to build a cascading style sheet model CSSOM (CSS Object Model)
  • Merge DOM Tree and CSSOM into one Render Tree
  • With Render Tree, the browser can obtain the CSS definition and affiliation of each node, so that it can calculate the actual position of each node
  • Drawing pages by calculation rules from the previous step

Virtual DOM refers to constructing the real DOM tree into the form of js objects, so as to solve the performance problem of the browser operating the real DOM.
Virtual DOM is to use the advantage of fast running speed of js to optimize the operation of DOM. Use js to simulate the DOM tree, and process the operation of DOM in js before rendering. A brief summary is divided into the following three points:

  • Simulate the DOM tree with javascript objects and render the DOM tree;
  • Compare the old and new DOM trees through the diff algorithm to obtain the object of the difference;
  • Applies the diffed object to the rendered DOM tree.

The diff algorithm is an efficient algorithm for comparing tree nodes at the same level.

  • Comparisons will only be performed at the same level, not cross-level comparisons
  • In the process of diff comparison, the loop compares from both sides to the middle
    insert image description here

4. Build the environment

How to build a vue project

5. Easy to use

After the Vue instantiation object is mounted to the root element, a global Vue object instance is generated. The Vue object will pass in the configuration object (options) during the instantiation process. The options include data, methods, computed, watch, etc.

  • For Vue to work, you must create a Vue instance and pass in a configuration object
  • The code in the root container still conforms to the html specification, but some special Vue syntax is mixed in
  • The code in the root container is called the Vue template
  • There is a one-to-one correspondence between Vue instances and containers , and the latter will not be substituted into Vue.
  • There is only one Vue instance in real development, and it will be used with components
  • The xxx in { {xxx}} needs to write a js expression, and xxx can automatically read all the attributes in data
  • Once the data in data changes, the place where the data is used in the template will also be automatically updated.

2. Grammar

1. Template syntax

There are two types of template syntax: text interpolation syntax and instruction syntax.

  1. Interpolation syntax: used to parse tag content
<div>{
   
   {xxx}}</div>
//xxx 是 js 表达式,可以直接读取到 data 中的所有区域
  1. Instruction syntax: used to parse tags (including: tag attributes, tag body content, binding events...)
  • v-html: insert as html;
<span v-html="xxx"></span>
  • v-bind: One-way data binding, data can only flow from data to page;
<div v-bind:id="dynamicId"></div>
简写为:
<div :id="dynamicId"></div>

动态绑定多个值:
<div v-bind="objectOfAttrs"></div>
data() {
  return {
    objectOfAttrs: {
      id: 'container',
      class: 'wrapper'
    }
  }
}
  • v-model: Two-way data binding, data can not only flow from data to pages, but also from pages to data; abbreviated v-model:valueas v-model; often used in form components.
<input type="text" v-model:value="name"><br/>
简写为
<input type="text" v-model="name">
  • v-if: This command removes/inserts the element based on the true or false value of the expression
<p v-if="seen">Now you see me</p>
  • v-on: Listen for DOM events, abbreviated as @characters
<a v-on:click="doSomething"> ... </a>

<!-- 简写 -->
<a @click="doSomething"> ... </a>

Dynamic parameters :
You can also use a JavaScript expression on the command parameter, which needs to be enclosed in a pair of square brackets:

<a v-bind:[attributeName]="url"> ... </a>

<!-- 简写 -->
<a :[attributeName]="url"> ... </a>
  • The value of the expression in the dynamic parameter should be a string, or null;
  • Spaces and quotes are illegal in HTML attribute names;
  • When using DOM inline templates (templates written directly in the HTML file), we need to avoid using uppercase letters in the name, because the browser will force it to be converted to lowercase.

2. Responsive Basics

data : When using the option API, the data option will be used to declare the reactive state of the component. The value of this option should be a function that returns an object. Vue will call this function when creating a new component instance, and wrap the object returned by the function with the reactive system. All top-level properties of this object will be proxied to the component instance (ie, this in methods and lifecycle hooks).

That is, data is a function called when creating a Vue instance. This function returns an object composed of the values ​​to be responded in the responsive component. The top-level properties of the object are linked to the component instance.

There are 2 ways to write data:

  • Object type: data: { }
  • Functional style: data() { return { } }
    How to choose: any writing method is acceptable at present, and when it comes to components in the future, data must use functions, otherwise an error will be reported.
    Functions managed by Vue must not write arrow functions, otherwise this will no longer be a Vue instance.

el :
el has 2 ways of writing

  • Configure the el attribute when creating a Vue instance object
  • Create a Vue instance first, and then specify the value of el through vm.$mount('#root')

3. MVVM model data agent

insert image description here
MVVM model

  • M: model Model, the data in data
  • V: view View, template code
  • VM: view model ViewModel, Vue instance

All the attributes in data finally appear on the vm;
all the attributes on the vm (that is, the Vue instance) and all the attributes on the Vue prototype can be used directly in the Vue template (big double brackets on the page).

Data Proxy : Proxy operations on properties in another object through one object (read/write)

Object.defineproperty (to whom to add attributes, attribute name, {configuration item})
configuration item:

{
    
    
	value:xx,
	enumerbale:true,//是否可枚举,默认false
	writable:true,// 是否可以被修改,默认值是false
    configurable:true// 是否可以被删除,默认值是false
	get(){
    
    }
	//当有人读取对象的该属性时,get函数(getter)就会被调用,且返回值就是该属性的值
	set(value){
    
    }
	//当有人修改对象的该属性时,set函数(setter)就会被调用,且会收到要修改的值
}

Data proxy in Vue :

  • The data proxy in Vue uses the vm object to proxy the operation of the properties in the data object (read/write)
  • The benefits of data proxy in Vue: more convenient operation of data in data
    Basic principles
  • Add all properties in the data object to the vm through object.defineProperty()
  • For each attribute added to the vm, specify a gettersetter
  • Operate (read/write) the corresponding attributes in the data inside the gettersetter

That is to say, when we create a vue instance, we pass in configuration items, where the data function returns a set of data, which is copied to the instance (vm) , and then uses the data in _datathe data function to proxy the data. In order to achieve data hijacking, implement data change monitoring, and notify Vue to render. It is written in Vue2: When a Vue instance is created, it adds all the properties in the data object to Vue's responsive system. When the values ​​of these properties change, the view will "response", that is, the matching will be updated with the new values._data_data
insert image description here

There are two ways to write data, but is it an object or a function?

4. Event handling

  • Use v-on:xxx or @xxx to bind events, where xxx is the event name
  • The callback of the event needs to be configured in the methods object, which will eventually be on the vm
  • For the functions configured in methods, do not use arrow functions, otherwise this will not be vm but point to window
  • The functions configured in methods are all functions managed by Vue, and this points to the vm or component instance object
  • @click="demo" has the same effect as @click="demo($event)", but the latter can pass parameters.

Event modifiers :
insert image description here
Modifiers can be used in conjunction:@click.prevent.stop=dosome

Keyboard events :

insert image description here

5. Computed properties

Attribute : the data in data, the former is the attribute name, and the latter is the attribute value.
Definition : The attribute to be used does not exist and needs to be calculated from existing attributes.
Principle : The bottom layer uses the getter and setter provided by the Objcet.defineproperty() method. The getter is called
when the value is first read and when dependent data changes .
The setter is called when the property is modified.

Advantages : Compared with the implementation of methods, there is a cache mechanism (multiplexing) inside, which is more efficient and easy to debug.

Computed property values ​​are cached based on their reactive dependencies. A computed property is only recomputed when its reactive dependencies are updated. Otherwise, the previous calculation result is returned immediately without re-executing the getter function. Method calls will always execute the function again when a re-render occurs.

  • Computed attributes will eventually appear on the vm, just read and use directly
  • If the computed property is to be modified, the set function must be written to respond to the modification, and the set will cause the data on which the calculation depends to change
  • If the computed property is determined not to consider modification , you can use the shorthand form of the computed property

Grammar :

computed{
    
    
	计算属性名:
	{
    
    	get(){
    
    },
		set(){
    
    }}
	}
new Vue({
    
    
	el:'#root',
	data:{
    
    
		n:12
	},
	computed: {
    
    
		//完整写法
      fun: {
    
    
      	get(){
    
    
      		return n++;
      	},
     	set(value){
    
    
     		this.n=value
     	}
      // 简写
      fun2() {
    
    
        return this.n++
      }
	}
})

6. Monitor properties

Computed attributes are calculated directly from existing attributes to obtain "new attributes", but if some derivative operations need to be performed on existing attributes, they cannot be completed.

A watch property is a function that fires every time a reactive property changes. Trigger a function to do something when an existing property to monitor changes.

watch monitoring properties

  • When the monitored property changes, the callback function handler is automatically called to perform related operations
  • The monitored attribute must exist before it can be monitored, either data or computed attribute can be monitored
  • The configuration item attribute defaults to immediate:false, if it is changed to true, the handler(newValue,oldValue) will be called once during initialization

There are two ways to write monitoring

  • Pass in watch when creating Vue: {} configuration
  • Monitoring via vm.$watch()
  const vm = new Vue({
    
    
    el: '#root',
    data: {
    
    
      isHot: true,
    },
    computed: {
    
    
      info() {
    
    
        return this.isHot ? '炎热' : '凉爽'
      }
    },
    methods: {
    
    
      changeWeather() {
    
    
        this.isHot = !this.isHot
      }
    },
    // 方式一
    /* watch:{		
			isHot:{
				immediate:true,
				handler(newValue,oldValue){
					console.log('isHot被修改了',newValue,oldValue)
				}
			}
		} */
  })
  // 方式二
  vm.$watch('isHot', {
    
    		
    immediate: true, // 初始化时让handler调用一下
    //handler什么时候调用?当isHot发生改变时
    handler(newValue, oldValue) {
    
    
      console.log('isHot被修改了', newValue, oldValue)
    }
  })

Multi-level monitoring :
use quotation marks directly for a value in the monitoring object'对象名.属性名'

const vm = new Vue({
    
    
    el: '#root',
    data: {
    
    
      number:{
    
    
		a:1,
		b:2
		}
    },
    watch:{
    
    		
		"number.a":{
    
    
				immediate:true,
				handler(newValue,oldValue){
    
    
				}
			}
		}
  })

Deep monitor :
watch is shallow by default: the monitored property will only trigger the callback function when it is assigned a new value-but the change of the nested property will not trigger. If you want to listen to all nested changes, you need deep listeners.

  • The watch in Vue does not monitor the change of the internal value of the object by default (one layer)
  • Configuration in the watch deep:truecan monitor the change of the internal value of the object (multi-layer)

Notice

  • Vue itself can monitor the change of the internal value of the object, but the watch provided by Vue cannot by default
  • When using watch, decide whether to use in-depth monitoring according to the specific structure of the monitoring data

Shorthand :
If the monitoring attribute has no other configuration items except the handler, it can be shorthanded.

 watch: {
    
    
      //简写
      isHot(newValue, oldValue) {
    
    
        console.log('isHot被修改了', newValue, oldValue, this)
      }

Computed Properties vs Listened Properties

  • The functions that can be completed by computed can be completed by watch

  • The functions that can be completed by watch may not be completed by computed. For example, watch can perform asynchronous operations.

  • All functions managed by Vue are best written as ordinary functions, so that the point of this is the vm or component instance object

  • For all functions not managed by Vue (timer callback function, ajax callback function, etc., Promise callback function), it is best to write arrow functions, so that the point of this is the vm or component instance object

7. Class and style binding

A common requirement scenario for data binding is manipulating an element's CSS class list and inline styles, using v-bind.

  • Writing method: :class="xxx", where xxx can be a string, an array, or an object
  • :style="[a,b]" where a and b are style objects
  • :style="{fontSize: xxx}" where xxx is a dynamic value
  • The string writing method is suitable for: the class name is uncertain, and it needs to be obtained dynamically
  • The array writing method is suitable for: to bind multiple styles, the number is uncertain, and the name is also uncertain
  • The object writing method is suitable for: to bind multiple styles, the number is determined, and the name is also determined, but it is not sure whether to use it or not
绑定数组
<div :class="[activeClass, errorClass]"></div>

绑定对象isActive
<div :class="{ active: isActive }"></div>

<!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 -->
  <div class="basic" :class="mood" @click="changeMood">{
   
   {name}}</div><br/><br/>

  <!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 -->
  <div class="basic" :class="classArr">{
   
   {name}}</div><br/><br/>

  <!-- 绑定class样式--对象写法,适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用 -->
  <div class="basic" :class="classObj">{
   
   {name}}</div><br/><br/>

  <!-- 绑定style样式--对象写法 -->
  <div class="basic" :style="styleObj">{
   
   {name}}</div><br/><br/>

  <!-- 绑定style样式--数组写法 -->
  <div class="basic" :style="styleArr">{
   
   {name}}</div>

8. Conditional rendering

v-if Directives are used to conditionally render a piece of content. This block will only be rendered if the directive's expression returns true. A v-elseelement must follow an v-ifor v-else-if element, otherwise it will not be recognized.

Want to toggle more than one element: In this case we can use v-if on one element, which is just an invisible wrapper element, and the final rendered result will not contain this element.

v-showAlso conditionally displays an element.

<h1 v-show="ok">Hello!</h1>

insert image description here
v-if 与 v-for

  • v-if is "true" conditional rendering because it ensures that event listeners and child components inside the conditional block are destroyed and recreated when toggled.
  • v-if is also lazy: if the condition evaluates to false on the first render, nothing will be done. Conditional blocks are only rendered when the condition first becomes true.
  • In contrast, v-show is much simpler, the element will always be rendered regardless of the initial condition, and only the CSS display property will be toggled.
  • Overall, v-if has a higher switching overhead, while v-show has a higher initial rendering overhead. Therefore, if frequent switching is required, v-show is better; if binding conditions rarely change at runtime, v-if is more appropriate.

9. List rendering

Use the v-for directive to render a list based on an array.

  • Used to display list data
  • Syntax: <li v-for="(item, index) of items" :key="index">, where the key can be index, better is the unique identifier of the traversal object
  • Traversable: arrays, objects, strings (less used), specified times (less used)

"(item, index) of items" :key="index" :
Traversing objects: the first is the attribute value, the second is the attribute name, and the third is the position index;
traversing the array: item in items

<li v-for="item in items">
  {
   
   { item.message }}
</li>
  <!-- 遍历数组 -->
  <h3>人员列表(遍历数组)</h3>
  <ul>
    <li v-for="(p,index) of persons" :key="index">{
    
    {
    
     p.name }}-{
    
    {
    
     p.age }}</li>
  </ul>

  <!-- 遍历对象 -->
  <h3>汽车信息(遍历对象)</h3>
  <ul>
    <li v-for="(value,k) of car" :key="k">{
    
    {
    
     k }}-{
    
    {
    
     value }}</li>
  </ul>

  <!-- 遍历字符串 -->
  <h3>测试遍历字符串(用得少)</h3>
  <ul>
    <li v-for="(char,index) of str" :key="index">{
    
    {
    
     char }}-{
    
    {
    
     index }}</li>
  </ul>

  <!-- 遍历指定次数 -->
  <h3>测试遍历指定次数(用得少)</h3>
  <ul>
    <li v-for="(number,index) of 5" :key="index">{
    
    {
    
     index }}-{
    
    {
    
     number }}</li>
  </ul>

v-for can accept an integer value directly. In this use case, the template is repeated multiple times based on a value range of 1…n.

<span v-for="n in 10">{
   
   { n }}</span>

Note that the initial value of n here starts from 1 instead of 0.

Use v-for on a tag to render a block containing multiple elements.

It is not recommended to use v-for and v-if at the same time, because there is no way to distinguish precedence.

You can use v-for directly on the component, but it will not automatically pass any data to the component, because the component has its own independent scope.

Key management :
By default, Vue updates the list of elements rendered by v-for according to the "in-place update" strategy. When the order of data items changes, Vue does not move the order of DOM elements accordingly, but updates each element in place to ensure that they are rendered at the originally specified index position.

The default mode is efficient, but only suitable for cases where the result of list rendering output does not depend on child component state or temporary DOM state (such as form input values).

So it is necessary to provide a unique key for the block corresponding to each element, so that it can track the identity of each node, thereby reusing and reordering existing elements.

insert image description here
Array management :

Change method: change the original array

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

replace array: returns a new array

  • filter()
  • concat()
  • slice()

Data monitoring :
This link explains it very clearly: Vue data monitoring
Simply put, it is

  1. Process the data object into a _data object: add responsive get and set methods (data proxy) to implement data hijacking and store it in the Vue instance;
  2. The Vue global instance object proxies the _data object to implement direct operations on the attributes in _data;
  3. Data change monitoring effect
    When each data with a reactive setter changes, the reactive setter will be called, and when the reactive setter is called, it will trigger re-parsing the template, generating a new virtual DOM, comparing the old and new virtual DOM, and updating the content mapping To the real DOM, re-rendering this set of processes.

Dynamically added attributes: Vue.set(targetObject, attributeName, attributeValue) method or this.$set(targetObject, attributeName, attributeValue) to dynamically add responsive attributes.

Vue does not add responsive getters and setters to array elements , so changes to array data through subscripts cannot be monitored by Vue.
For arrays, only by calling the seven APIs of push, pop, shift, unshift, splice, reverse, and sort to change the original array itself, will Vue respond.
insert image description here

Guess you like

Origin blog.csdn.net/qq_46056318/article/details/127541387