Moment For Technology

Vue system | all kinds of basic knowledge and details

Posted on Sept. 23, 2022, 3:38 p.m. by Kayla Long
Category: The front end Tag: vue.js The front end

directory

  • Vue Foundation
  • vue-cli
  • vue-router
  • vuex
  • element-ui
  • vue3

1. Introduction of vue

1.1 What is a VUE

A set of progressive JavaScript frameworks for building user interfaces

Front-end responsibilities: Make the right requests at the right time to put the data in the right place

  • Progressive: VUE can be applied from the bottom up
  • Simple application: a lightweight, compact core library is required
  • Complex applications: Various Vue plug-ins can be introduced

The Vue's website

Introduced the CDN

The vue2 version uses the following one

 script SRC = "https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"   / script Copy the code

1.2 Features of Vue

  1. Componentized mode is adopted to improve code reuse rate and make code easier to maintain.
  2. Declarative coding eliminates the need for coders to directly manipulate DOM and improves development efficiency

1.3 What basic knowledge of JavaScript should be mastered before learning Vue

  • ES6 syntax specification
  • ES6 modular
  • A package manager
  • Prototype, prototype chain
  • Common methods for arrays
  • axios
  • promise
  • .

1.4 What to know about VUE for the first time

  • For Vue to work, you must create an instance of Vue and pass in a configuration object
  • The code in the root container is still HTML compliant, but with some special Vue syntax mixed in
  • The code in the root container is called the Vue template.
  • Vue instances and containers are one-to-one
  • There is only one instance of Vue in real development and it is used with components
  • XXX in {{XXX}} will write js expressions, and XXX can automatically read all attributes in data
  • Whenever the data in the data changes, the use of that data in the template is automatically updated

2. Core foundation of VUE

2.1 Template Syntax

Vue's template syntax falls into two broad categories:

  1. Difference syntax:
  • Function: Used to parse label body content
  • {{XXX}}, XXX will be parsed as the tag body, and can automatically read the attributes in data
  1. Instruction syntax:
  • Function: Used to parse tags (including: tag attributes, tag content, binding events...)

2.2 Data Binding

One-way data binding (V-bind)

Data can only flow from data to the page

Two-way data binding V-Model

Data can flow not only from data to pages, but also from pages to data


summary

  • V-models are typically applied to form elements and have values

2.3 Two ways of writing EL and data

El can be written in two ways:

  1. The first:
New Vue ({el:'#root', data:{MSG :'#root'}})Copy the code

The second, less common:

        const vm = new Vue ({
            data:{
                msg:'xiba'
            }
        })

        vm.$mount('#root')
Copy the code
  1. There are two ways to write data:

The first type: object type

The first way to write it,data is an object

Data :{MSG :' xiaoshuai '}Copy the code

The second type: functional

The second way of writing data is that data is a function that returns a data object.

            data(){
                return {
                    msg:'xiba'
                }
Copy the code

Componentization must use functional data

  1. An important principle

For functions managed by Vue, do not write arrow functions. Once arrow functions are written, this is no longer a Vue instance. Become a window

2.4 MVVM

  1. M: Model: data in corresponding data
  2. V: View: template code
  3. VM: ViewModel: An instance object of Vue

My understanding:

So Model is what's in the refrigerator, for example, a watermelon is data, view is where you look at the watermelon in the refrigerator, viewModel is the refrigerator, right

Observation shows that

  1. All of the attributes in data end up in the VM.
  2. All attributes on the VM and all attributes on the Vue prototype can be used directly in the Vue template.
div id="root" ! - this is the view -   div  {{name}}  / div   / div   script SRC = "https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"   / script  script // here is ViewModel new Vue({el:'#root', // here is Model data:{name:'xiba'}})Copy the code

What does a VUE instance do

By data binding and data listening

2.5 Data Agent

Data proxy: Operations (read/write) on properties in another object through one object proxy

  1. Data broker in Vue:

Proxy operations (read/write) on properties in data objects through VM objects

  1. Benefits of data brokers in Vue:

More convenient operation of data in data

  1. Basic Principles:

Add all attributes from the data object to the VM via Object.defineProperty (). Specify a getter/setter for each property added to the VM. To manipulate (read/write) the corresponding property in data inside the getter/setter.

2.6 Event Handling

2.61 Basic Use of events:

  1. Bind events with V-on :XXX or @xxx, where XXX is the event name;
  2. Callbacks to events need to be configured in the Methods object, which will eventually be on the VM;
  3. Functions configured in methods. Don't use arrow functions! Otherwise this would not be vm;
  4. All functions configured in Methods are functions managed by Vue. This refers to vm or component instance objects.
  5. @click=" XXX "; @clicl=" XXX ($event) ";

2.62 Event modifier

Event modifiers in Vue:

  1. Prevent: prevent default events.
  2. Stop: the event bubbles (often used);
  3. Once: The event is triggered only once (common):
  4. Capture: Capture mode using events;
  5. Self: Fires an event only if event.target is the element of the current operation;
  6. Passive: The default action of the event is executed immediately without waiting for the event callback to complete.

2.63 Keyboard Events

  1. Common key aliases in Vue:
  • Enter = enter
  • Delete = delete(insert delete and backspace keys)
  • Exit = esc
  • Space = space
  • Newline = TAB (special, must be used with keyDown)
  • = on the up
  • = down under
  • L = left
  • = right right
  1. Vue does not provide keys for aliases. You can unbind the keys using the original key value, but make sure to convert to kebab-case(short line name).
  2. System modifier keys (special usage) : CTRL, Alt, Shift, Meta
    1. Used with keyUp: Press the modifier key at the same time, then press the other keys, then release the other keys, the event is triggered.
    2. Used with KeyDown: Events are normally triggered.
  3. You can also use keyCode to specify specific keys (not recommended)
  4. Vue.config.keycodes. custom key name = key code, you can customize key alias

2.7 Calculating Attributes

Calculated attributes:

  1. Definition: the attribute to be used is not present, and is computed from an existing attribute
  2. How it works: The bottom layer uses getters and lsetters provided by objcet.defineProperty methods.
  3. When is the get function executed?
    1. It is executed once on the first read.
    2. It is called again when the dependent data changes.
  4. Advantages: Compared with methods implementation, internal caching mechanism (reuse), higher efficiency, convenient debugging.
  5. Remark:
    1. The calculated properties will eventually appear on the VM and can be read and used directly.
    2. If the calculated property is to be modified, the set function must be written in response to the modification, and the set function must cause the data on which the calculation depends to occur

You can abbreviate it as a function

2.8 Monitoring Properties

Monitor property Watch:

  1. When the monitored property changes, the callback function is called automatically to perform the related operation
  2. The monitored properties must exist. To conduct surveillance!!
  3. Two ways to write monitoring:
    1. The Watch configuration is passed in for new Vue
    2. Monitor through vm.$watch

Deep monitoring:

Deep :true monitors data changes in multilevel structures

Watch :{XXX :{immediate:true // Initialize deep :true // handler(newValue, oldValue){}}}Copy the code

Differences between computed and LWatch:

  1. The watch can do what computed can do.
  2. For example, with computed, the watch can perform asynchronous operations.

Two important principles: |

  1. Vue-managed functions are best written as normal functions so that this refers to a VM or component instance object.
  2. All functions not managed by Vue (timer callbacks, Ajax callbacks, etc.) are best written as arrow functions so that this points to the VM or component instance object.

2.9 Binding Styles

The binding class

Three methods

  • String writing

For: Style class names are indeterminate and need to be specified dynamically

        div class="basic" :class='mood' @click="changeMood"{{name}}/div

            data:{
                name:'xiba',
                mood:'happy'
            },
Copy the code
  • An array of writing

Applies to: the number of styles to bind is not determined, the name is not determined --

        div class="basic" :class="classArr[1]"{{name}}/divbr

                classArr:['happy','sad','normal'],

Copy the code
  • Object to write

Applies to: the number of styles to bind and the name are determined, but dynamically decide whether to use them

        div class="basic" :class="classObj"{{name}}/div


                classObj:{
                    happy:false,
                    normal:true

                }
Copy the code

The binding style

The way you write an object

3.0 Conditional Rendering

Conditional rendering:

  1. v-if

Writing:

  1. V-if =" expression"
  2. V-else -if= "expression"
  3. V else=" expression"
  • Applicable to: Scenarios with low switching frequency.
  • Features: DOM elements that are not shown are removed.
  • Note: v-if can be used with :v-else-if and v-else, but the structure must not be "broken".
  1. v-show

V-show =" expression"

  • Applicable to: Scenarios with high switching frequency.
  • Features: DOM elements that are not displayed are not removed, just hidden with styles

3. Note: If v-if is used, elements may not be obtained. If v-show is used, elements must be obtained.

3.1 List Rendering

V - for instructions:

  1. For display list data
  2. V-for ="(item,index) in XXX ": key="yyy"
  3. Traversable: arrays, objects, strings (rarely used), specified times (rarely used)

3.11 Functions and Principles of key

Key functions:

When the data changes, vue generates a new virtual DOM based on the new data, which is compared to the old DOM

Rules of comparison:

Look at the key, look at the content,

The key is the same:

  • I'm going to use the same real DOM as before
  • The content changes and a new real DOM is generated, replacing the old real DOM

The key difference:

Create a new real DOM and then render the page

The index key problem:

  1. Out-of-order operations, such as reversing the data, can result in unnecessary real DOM updates, affecting efficiency
  2. Dom with input classes will generate incorrect DOM updates, causing interface problems

How to select key in development:

Use unique identifiers

3.12 List Filtering

It's kind of a fuzzy search

You can do both with watch and computed, but watch is a little bit more complicated than computed

computed: {filpersons() {return this.persons.filter((p) = {// Return this to persons.indexof (this.keyword)! == -1 // Return filtered results})}}Copy the code

3.13 List Sorting

Implemented using computed properties

Create a new array and sort the new array

computed: { filpersons() { const arr = this.persons.filter((p) = { return p.name.indexOf(this.keyWord) ! == -1 }) if (this.sortType) { arr.sort((a, b) = { return this.sortType === 1 ? b.age - a.age : a.age - b.age }) } return arr } }Copy the code

3.2 Principle of VUE monitoring data

Through the get and set methods in Object.defindeProperty

The data in data will be processed, get will be automatically called when reading, set will be used to modify, and then the data will be told to Wacher, and the old and new DOM will be compared and rendered again

Vue monitoring data principle:

  1. Vue monitors all levels of data in data.
  2. How do I monitor data in objects?

Monitoring is implemented through setters and the data to be monitored is passed in at new Vue.

By default,Vue does not respond to newly added attributes. 2. To respond to newly added attributes, use the following API:Copy the code

Vue. Set (target) propertyName/index) value) or vm. $set (value) target. PropertyName/index.

  1. How do I monitor the data in an array?

    By wrapping the array update element, we essentially do two things:

    1. Call the native corresponding method to update the array
    2. Reparse the template to update the page.
  2. To modify an element in a Vue array, do the following:

Using these apis:

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

2. Vue. The set () or vm. $set ()

Special note :Vue.set() and vm.$set() cannot add attributes to the VM or the root data object of the VM!

Vue data hijacking is when you modify data, vue catches you, he uses set to modify it for you, and then throws it back on the web page

3.3 How to use V-Model to collect form data

Collect form data:

  • If input type="text"/, then the V-model collects values and the user enters values.
  • If:, then V-Modei collects values and configures values for labels.
  • If:
  1. If the value attribute for input is not configured, checked is collected.
  2. Configure the value attribute for input:
    1. The initial value of the V-model is not an array, so checked is collected.
    2. The initial values of the V-model are arrays, so the collection is an array of values

Note: Three modifiers for v-model:

  • Lazy: Data is collected after losing focus
  • Number: Converts the input string into a valid number
  • Trim: Enter the first and last Spaces

3.4 the filter

Vue3 has been removed

3.5 v - text

V - text instructions:

  1. Function: Renders text content to its node.
  2. Difference from interpolation syntax: V-text replaces the contents of a node, {{xx}} is unfair.

3.6 Cookie Tips

It's like our ID card is very important, the server gives us, through this identification to make the identity

How to get someone else's Cooki?

A link, jump, A

3.7 VUE built-in instructions

3.71 v - HTML

  1. V-html can recognize HTM1 structures.
  2. Serious note: V-HTML has security issues!!!!
    1. Dynamically rendering arbitrary HTML on a website is very dangerous and can lead to XSS attacks.
    2. Always use V-HTML for trusted content, not user-submitted content!

3.72 v - cloak

V-cloak instruction (no value) :

  1. The v-cloak property is a special property that will be dropped when the Vue instance is created and takes over the container.
  2. The PROBLEM that {{xXx]} is displayed when the network speed is slow can be solved by using CSS and V-cloak.

3.73 v - once

V - once the instructions:

  1. The v-once node is treated as static after the first dynamic rendering.
  2. Future data changes will not cause the update of the v-once structure, which can be used to optimize performance.

3.74 v - pre

V - pre instructions:

  1. Skip the compilation of its node.
  2. It can be used to skip: nodes that do not use instruction syntax and interpolation syntax will speed up compilation.

3.8 Custom Commands

Summary of custom instructions:

1. Define the syntax:

  1. Local instructions:

New vue directives:{directive name: configured object} or

Directives (){directives: callback function}

            directives:{
                big(element,binding){
                    console.log('big')
                    element.innerText = binding.value * 10
                },
                fbind:{
                    bind(){

                    },
                    inserted(){},
                    update(){}
                }
            }
Copy the code

}) 2. Global directive: vue. directive(directive name, configuration object) or vue. directive(directive name, callback function)

Configure the three common callbacks in the object:

  1. Bind: called when a directive is successfully bound to an element.
  2. Inserted: Called when the element of the directive is inserted into the page
  3. Update: called when the template structure of the directive is reparsed.

Iii. Remarks:

  1. Instructions are defined without v-. But use v-;
  2. If the instruction name is multiple words, use kebab-case instead of camelCase.

3.9 VUE life cycle

Life cycle:

  1. Also known as: number of lifecycle callbacks, lifecycle functions, lifecycle hooks.
  2. What it is: Some specially named functions Vue calls for us in the Nick of time.
  3. The name of a lifecycle function cannot be changed, but the details of the function are written by the programmer as required.
  4. The this in the lifecycle function refers to the VM or component instance object.

Common lifecycle hooks:

  1. Mounted: Sends ajax requests, starts a timer, associates custom events, and subscribs messages.
  2. BeforeDestroy: Clear timers, unbind custom events, unsubscribe messages, and so on.

About destroying Vue instances:

  1. You can't see any information with Vue developer tools after destruction.
  2. Custom events are invalidated after destruction, but native DOM events are still valid.
  3. You typically do not manipulate data beforeDestroy, because even if you manipulate data, the update process is no longer triggered.
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.