At its heart, vue.js is a system that allows declaratively rendering data into the DOM using a concise template syntax.

introduce

Let’s talk about Vue framework data rendering (data binding) with DOM tree.

Text nodes render data

By interpolation: {{}}

Property node renders data

By: v – bind: attribute

DOM structures render data

The value can be V-if, V-show, or V-for

interaction

Vue uses V-ON to add event listeners and invoke methods defined in the instance to allow users to interact with the application.

The instance

Vue components are all Vue instances and accept the same option objects (except for options specific to the root instance).

Data and Methods

When a Vue instance is created, it adds all the parameters from the data object to the Vue’s response system. When the values of these parameters change, the view responds.

Parameters in a data object that already exists are reactive only when the Vue instance is created.

Exception: Object.freeze() prevents modifying the values of parameters in a data Object

       let obj = {
            message: 'hello world'
        }
        Object.freeze(obj)
        var vm = new Vue({
            el: '#app'.data: obj
        })
Copy the code

Unable to assign object to message with read-only property

The life cycle

The this of the lifecycle hook points to the Vue instance calling it.

Do not use arrow functions on option methods or callback functions, because arrow functions do not have this. This will be used as a variable to search the upper lexical scope until it is found, often resulting in an error.

        var vm = new Vue({
            el: '#app'.data: {
                message: 'hello world'
            },
            created: () = > {
                console.log(this.message)
            }
        })
Copy the code

Template syntax

The interpolation

<span v-once>{{message}}</span>
Copy the code

V-once interpolates once. When the data changes, the content of the interpolation is not updated.

v-html

Arbitrary HTML rendered dynamically on your site can be very dangerous because it can easily lead to XSS attacks. Use HTML interpolation only for trusted content, never for user-supplied content.

attribute

<input v-bind:disabled="show" type="text">
Copy the code

For Boolean attributes such as disabled, their presence means they are disabled, but v-bind is slightly different. If show is null, false, or undefined, disabled will not work or even render.

Using JavaScript expressions

For all data bindings, Vue provides full JS expressions. {{message + 1}} {{a+1>0 ? Yes: no}} <span :id=”‘item’ + id”>, these expressions are parsed as JS in the data scope of the owning Vue instance, there is a limitation that each binding can contain only a single expression, {{var a = 1}} is not supported.

Template expressions are sandboxed and can only access a whitelist of global variables, such as Math and Date, {{Date()}}, and no attempt should be made to access user-defined global variables in template expressions.

Instruction-dynamic parameters

<div@ [handlename] ="value"></div>
Copy the code

The dynamic parameter is expected to evaluate a string, null in exceptional cases, which can be explicitly used to remove the binding, and any other string value will trigger a warning.

        var vm = new Vue({
            el: '#app'.data: {
                message: 'hello world'.name: "123"}})Copy the code

Failed to execute setAttribute on element: 123 is not a valid attribute name.

        var vm = new Vue({
            el: '#app'.data: {
                message: 'hello world'.name: 1}})Copy the code

Dynamic instruction parameter invalid value (expected string or NULL)

Specification of dynamic parameter expressions: Do not use Spaces and quotes (use expressions without Spaces and quotes or replace complex expressions with computed attributes), and avoid uppercase letters

The modifier

Used to indicate that an instruction should be bound in a particular way.

Evaluate properties and listeners

Evaluation properties should be applied to expressions in templates whenever there is complex logic.

Computed properties are cached based on reactive dependencies and are recalculated only when the associated reactive dependencies change.

The method names in the computed property object can be used directly as data parameters. (Vue instance will look in data first, if not found, it will look in calculated properties)

computed:{
    now: function(){
        return Date.now()
    }
}
Copy the code

Calculate the property cache vs method

methods:{
    now: function(){
        return Date.now()
    }
}
Copy the code

Now and now () have the same value, in contrast, calling a method, which will always be executed again whenever a re-rendering is triggered, is better for performance. Getter and setter


computed: {now: {
        get: function(){
            return Date.now()
        }
        set: function(newValue){ // Execute when the now value changes
            console.log(value)       
        }
    }
}
Copy the code

The listener

Computed properties are better than listeners in most cases. However, listeners are better suited for asynchronous or expensive operations when data changes are required.

Listeners also have a cache and will only re-execute if they are listening for changes in data.

 <div id="app">
    <input type="text" v-model="message">
 </div>
<script>
let vm = new Vue({
  el: '#app'.data: {
    message: 'Hello',},watch: {
    message: function (newQuestion,oldQuestion){
      console.log(newQuestion,oldQuestion)
      this.message = "new Hello"
      console.log("Latest value to be displayed ↓")
      console.log(newQuestion,oldQuestion)
    }
  }
})
</script>
Copy the code

Class is bound to Style

The HTML syntax is as follows:

<style>
    .home{color: red; }</style>
<div style="color:red;">hello world</div>
Copy the code

Object syntax

<div :class="{active: isActive, item: isItem}" class="home"></div>
Copy the code

The active and item(class name) styles take effect depending on the values of isActive and isItem. The :class and class attributes can exist together.

As an alternative shorthand, you can use the value of the classObj parameter to determine what style you want to display.

<div :class="classObj"></div>
<script>
data: {
    classObj: {
        active: true.item: null}}</script>
Copy the code

We can also bind a computational property of the returned object in the classObj, which is a common and powerful pattern.

Array syntax

<div :class="[home, item]">{{message}}</div>
<script>
data: {
    home: ' '.item: 'classItem'
}
</script>
Copy the code

Elements in the array, like variables, home is empty, so class style is classItem.

Use object syntax in arrays

<div :class="[home, {active: isActive}]"></div>
Copy the code

Style object syntax

<div :style="{color: colorValue, fontSize: sizeValue}"></div>
<script>
    data: {
        colorValue: 'red'.sizeValue: '80px'
    },
</script>
Copy the code

Or bind style objects

<div :style="styleObj"></div>
<script>
    data: {
        styleObj: {colorValue: 'red'.sizeValue: '80px'}},</script>
Copy the code

Style array syntax

div :style="[colorValue, sizeValue]">hello</div>
<script>
    data: {
        colorValue: {color: 'green'.fontSize: '30px'
        },
        sizeValue: {
            lineHeight: '50px'}},</script>
Copy the code

:style array syntax that applies multiple object data to an element.

Conditions apply colours to a drawing

<template v-if="show">
    <div>...</div>
    <div>Conditions apply colours to a drawing</div>
</template>
Copy the code
<div v-if="show"></div>
<div v-else-if="show1"></div>
<div v-else></div>// Need to be used close togetherCopy the code

Whole block show hide can be used with Tempalte as invisible wrap elements (V-if does, V-show does not). For frequent switching, you are advised to use v-show or v-if.

The list of rendering

<div v-for="(item, index) in items" :key="item.id">{{item}}</div>
<div v-for="(value, key, index) in items">{{value}}</div>
Copy the code

Key value, index is not recommended, because the frequent operation of data corresponding to index still costs performance, so Vue cannot fully reuse nodes.

Three ways to update an array

1. Change methods (push, POP, Shift, unshift, reverse, splice, sort)

These array methods trigger view updates.

2. Replace arrays

vm.items = []  // reassign
Copy the code

3. Set mode

// The first argument is the specific array object, the second argument is the index, and the third argument is the changed value
Vue.set(vm.items, 0.8)
vm.$set(vm.items, 0.1)
/ / object
Vue.set(vm.items, "name"."Lee")
vm.$set(vm.items, "name"."Lee")
Copy the code

Objects can be changed in two ways: reassignment and set methods.

V-for and evaluate properties

<script>
    data: {
        list: [1.2.3.4.5.6]},computed: {
        items: function(){
            return this.list.filter(function(item){
                return item % 2= = =0
            })
        }
    }
</script>
Copy the code

Similar to v-if, a <template> loop with v-for can be used to render a section of content with multiple elements.

The event processing

This refers to the current Vue instance in the method. An event is a native DOM event.

    methods: {
        addNewTodo: function (event) {
            console.log(this.name)
            console.log(event)
        }
    }
// You can also call the method vm.addNewtodo () with Js.
Copy the code

Event modifier

.stop Prevents the click event from being propagated

.once The click event is triggered only once

.prevent

.self 

Passive does not want to prevent the default action of the event

.capture

Key modifiers: When listening for keyboard events, you need to check for detailed keys

<input v-on:keyup.enter="submit">
// The submit method is called only when the Enter key is clicked
Copy the code

. Exact Specifies the exact system modifier

<button v-on:click.ctrl.exact="onCtrlClick">A</button>
// Only press CTRL and click to execute
Copy the code

Form input binding

<input type="checkbox" v-model="check">// Multiple checkbox binding values are arrays, and the array elements are the values of a single checkboxCopy the code

Form values can be bound to :value, and custom values can be passed

<input type="radio" v-model="radio" :value='a'>
<script>
    data: {
        radio:' '.a:'yes'
    }
// When the checkbox is selected, the value of radio is yes
</script>
Copy the code

The modifier

.lazy change event, which triggers data updates (default is input event)

 <input type="text" v-model.lazy="message">Lazy The value of message is updated only when the input is finishedCopy the code

.number can convert a bound value to a numeric type

<input v-model.number="age" type="number">/ / typeof (age) is a numberCopy the code

. Trim Automatically filters the first and last whitespace characters entered by users

<input type="text" v-model.trim="message">// If 'name' is entered, message is 'name'Copy the code

Component based

Each component maintains its data independently, because each time a component is used, a new instance of it is created.

The component’s data must be a function that returns data so that components have separate data stores.

// This is a global component
Vue.component('item', {template:'<div>{{message}}</div>'.data: function(){
        return {
            message: 'wenmeichao'}}})Copy the code

Value transfer between parent and child components: Parent and child components pass values to their children through properties, which receive values through props. The child sends a value to the parent via $emit (‘change’, parameter), which is received by the parent @change=”handle”.

Each component must have only one root element.

Considerations when parsing DOM templates

1, table UL/LI select tag used component, may cause parsing error, use IS to solve

<table>
    <custom-input></custom-input>
</table>
<script>
    Vue.component('custom-input', {
        template: '<tr><td></td></tr>'})</script>
Copy the code

The contents of the component do not appear in the table as expected, because the HTML encoding specification uses only tr tags in the table tag, not <custom-input> tags

Solution:

<table>
    <tr is="custom-input"></tr>
</table>
Copy the code

 Use the IS attribute, which conforms to the coding specification and renders the component.