Vue basis

What is the vue

Vue is a set of progressive javascript frameworks for building user interfaces

What is incremental

Incremental: Incremental enhancement, where a portion of vUE’s functionality can be used in a project, or the entire VUE bucket can be used to manage the project

What is a framework

A framework is a complete set of solutions with certain rules that need to be followed when used.

What is the MVVM

MVVM is a software architecture pattern

M: Model Data model (Ajax acquired data)

V: View (page)

VM:ViewModel

MVVM uses bidirectional data binding to enable automatic bidirectional data synchronization without DOM manipulation

What is componentized thought

** Componentization :** A component contains (HTML + CSS + JS), which divides a complete page into multiple components.

Vue development is componentized development, dividing a complete page into small parts based on function

Advantages of components :1. Easy maintenance 2

Vue basic syntax

Interpolation expression

Syntax :{{variable name or data}}

Ternary operators are supported. Expressions can be used, but not in tag attributes

Example code:

<templete>

	<div>
    	{{msg}}
    </div>

</templete>

<script>
	data(){
        return{
            msg:"hello Vue"
        }
    }

</script>
Copy the code

Vue instructions – v – bind

Action: Dynamically sets the value of a property

Grammar: < a v – bind: href = “url” > < / a >

Href =”url address”

Vue instructions – v – on

Function: Registers events

@click=” function name”

Common modifiers:

  • .prevent Prevents default behavior
  • .stop prevents bubbling

Get event objects

There are two cases:

  • Event functions do not take arguments. Functions in methods can be received directly using e
  • If the event function takes an argument, you need to use event; ‘@ click = fn (parameter 1, event; ` @ click = fn (parameter 1, event; ‘@ click = fn ` (parameter 1, event)

Key modifier

Enter, and.esc returns. Listen to see if the key is triggered

V-if and V-show: Box show and hide

V-if =” Boolean “, principle: frequently create and delete element nodes

V-show =” Boolean “, principle: set CSS style,display:none;

v-model

Role: Used with form elements to set two-way data binding

Note: V-Model ignores the original value, checked, and other initial values of the form elements

Modifier for v-model

  1. Number: Automatically converts the entered value to a number. If the value cannot be converted, the original value is returned
  2. Tirm: automatically filters the first and last blank characters entered by users
  3. Lazy: updates at chang time but not input time

v-text&v-html

V-text is like innerText in that it does not parse labels when inserting data

V-html is like innerHTML and parses the tag

V – a for loop

Function: Iterate over groups and objects

Syntax :v-for=”(item,index) in array “:key=” unique value”

Setting a key improves the comparison reuse performance of the virtual DOM

What is the virtual DOM

Virtual DOM: Essentially, JS objects that store node information, attributes and content to describe the real DOM.

Vue local reuse strategy: VUE will be local (same level, same location) as far as possible, compared with virtual DOM, reuse the old DOM structure for differentiated update

What is the Diff algorithm

  • Strategy 1:

    Compared with the root element of the same level, if the root element changes, it will not be reused, directly delete reconstruction

    If the root element does not change, then you can only recurse down if the property changes

  • Strategy 2:

    If key’ is specified, elements with the same key will be compared

V-bind enhancements to style handling

  1. Enhancements to class

    :class=”{class name 1: Boolean}”, add class if Boolean is true,false remove class

    :class=”[class name]”, add the class to the array

  2. Enhancements to style

    :style=”{attribute name: attribute value}”

Vue advanced syntax

The filter

Filters: Commonly used for text formatting. Can be used for interpolation and v-bind

Method of use: by | pipe, make calls; For example: {{MSG | filter}}

How to define a filter:

  1. Local filters: can only be called within the current component

    export default {
    	filters{method (){function content}}}Copy the code
  2. Global filters: Registered in main.js, can be used in individual components

    Vue.filter("Filter".function(){method contents})Copy the code

Calculate attribute

** Computed :** Computed property is an attribute, written as a function, that must return a value

Features: After calculating attributes, the results are cached. If the calculated attributes are used repeatedly, the cached results are directly used, improving performance

Use of computed attributes:

Shorthand mode: computed:{function (){returnComputed :{method (){get(){
            returnResults},set(){... }}}Copy the code

Event listeners

Watch: Use watch when the data to be monitored changes

Grammar:

watch:{
	// Data to be monitored
    list: {deep:trueIf you want to listen on complex data types, set deep to true
        handler(value){//value is the changed data monitored}}Copy the code

Componentized development

What is componentized development

Componentized development: using the idea of encapsulation, encapsulate reusable parts into components for easy development and maintenance.

The component registration

Component registration includes global registration and local registration. Note that the registered component name cannot be the same as the name of the built-in label

There are two ways to name components. The second is recommended

  1. Dash naming:hm-header
  2. Large hump nomenclature:HmHeader

Local registration: can only be used within the current component

Grammar:

Importing components:importComponent namefromComponent Addressexport default {
	components:{component name: component}}Copy the code

Global registration: Introduces components in main.js

Global Registration: Vue.com Ponent (Name, component)Copy the code

Resolve component style conflicts

By default, uninstalling styles within components takes effect globally

Adding the scoped attribute to a locally registered component makes the style apply only to the elements of the current component;

How it works: a custom property is automatically added, and when scoped is added, the style selection is also added with the corresponding property selector

Component communication

Parent to Son -props communication

The parent component adds attributes to the child component

// father.vue
<Son :title="info" price="100"></Son>
Copy the code

The child component receives the corresponding properties through props

//Son.vueexport default { props:{ title:{ type:String, default:"hello", required:true }, price:{ type:Number, required:true } }}
Copy the code

Unidirectional data flow

Vue follows the principle of one-way data flow:

1. Changes in parent component data affect child component data

2. A child component cannot directly modify the data transmitted by the parent component. The props is read-only

Note: Even if modified, no error will be reported, but should be avoided

Child parent – $emit

The child component fires the event via this.$emit(event name, parameter) and passes the parameter to the parent component for action modification

this.$emit("changeState".1);
Copy the code

The parent component needs to register a custom event on the child component with the same name as the event passed by the child component

//father.vue
      export default { methods:{ changeSt(){ ... }}}
Copy the code

Life cycle function

Lifecycle functions: Built-in functions provided by the VUE framework are automatically executed in sequence along with the lifecycle of components

Component lifecycles fall into three broad categories:

  • Initialization phase (data initialization + DOM rendering)
  • Run phase (data update)
  • Destruction phase (component destruction)

There are eight life cycle functions, focusing on Create and Mounted

1. BeforeCreate :data The component does not have data before the data is initialized

2. Created: After data initialization, component data has been obtained

BeforeMount: The DOM is not rendered before the DOM is rendered

Mounted: After rendering the DOM, you can manipulate the DOM

BeforeUpdate: Data is updated, before DOM is updated

6. Updated: Data updated,DOM updated

7. BeforeDestroy: Before component destruction

8. Destroyed: After the component is destroyed

axios

The underlying axios is Ajax, wrapped in promise

Basic usage syntax:

// add axios from axiosaxios({method:"get",//get,post url: // Data is split between get and POST requests. }, params:{//get request when concatenated to the request line... }}).then().catch()
Copy the code

Components into the order

$refs and ref

Ref and $refs can be used to obtain dom elements or component instances

Just add the ref attribute to the element or component you want to fetch and get it through this.$refs.xx

$nextTick

Because the VUE is asynchronously updated to the DOM (which improves rendering efficiency), sometimes the actual DOM is not successfully rendered after the data update is performed

With $nextTick, you can wait for the component’s DOM to refresh and then execute the callback function to ensure that the latest DOM element is accessed

Dynamic component

Multiple components use the same mount point, dynamically switching

Syntax :

Dynamic switching is implemented by dynamically changing the value of the component name

Keep-alive caches components and toggle components are not destroyed (by default toggle dynamic components are destroyed and then rebuilt)

slot

Slot A slot is a placeholder that occupies a position

The slot is used to distribute the content of the component. It can accept the content written in the label of the component

The default slot

If no content is passed :

Default content
displays the default content

A named slot

Give slots names when they are used

<slot name="header"></slot>

Use templete to wrap the content to be passed in the parent component, using the # slot name. Specify to whom the content will be distributed

<templete #header>	<h1>I'm the header content</h1></templete>
Copy the code
Scope slot

A value can be passed as an attribute through a scope slot

<slot :yes="yes" money:100></slot>// The added attributes are collected into an object {yes: ",money:100}// receive via # slot name = "obj" in templeteCopy the code

Custom instruction

derective

directives: {  // define a local directive color: Inserted (el, {value}) {el.style.color = value}, // Triggered when the value of update instruction changes, Update (el, binding) {el.style.color = binding.value}}}
Copy the code

Routing navigation

What is routing

Routing is a mapping between the hash value (#hash) of the URL in the browser and the component

Implementation principle of handwritten front-end routing

Ideas:

  1. The user clicked on the routing link on the page
  2. The Hash value in the URL address bar changes
  3. The front-end route listens for changes to the Hash address
  4. The front-end route renders the component corresponding to the current Hash address to the browser

vue-router

Based on experience, VUE components are divided into two types:

  1. Page component – Used for page display and routing
  2. Reuse components – Present data that can be reused
Vue-router Use (7 steps)
  1. Install YARN add VUe-router
  2. The introduction of the import
  3. Using the Vue. Use ()
  4. Create an instance
  5. mount
  6. Configuring Routing Rules
  7. Setting routing Egress