Vue.js framework foundation

T1: First acquaintance with vue.js

Select the Vue. Js

Disadvantages of traditional development:

  • Frequent DOM manipulation
  • DOM manipulation is mixed with logical code and is not maintainable
  • Different functional areas of the code written together, poor maintainability
  • The dependencies between modules are complex

Vue. Js core features

Data-driven view
  • Single-item data binding: Data changes are automatically updated to the corresponding element without manual manipulation of the DOM.
  • Two-way data binding: Applies only to inputable elements. Data is automatically rendered to the page, and element content changes can be updated to the data.

Advantages: Data-driven view based on MVVM model liberates DOM operations; View and Model processing are separated, reducing code coupling

Disadvantages: Bug debugging becomes more difficult in bidirectional binding; Large projects have too many Views and models and high maintenance costs

Componentized development
  • Allows web page functions to be encapsulated as custom HTML tags, which can be reused by writing custom tag names, improving code reusability.

  • Components can encapsulate not only structure, but also style and logic code, greatly improving development efficiency and maintainability.

A preliminary use of vue.js

Install the Vue # 3

  • Local introduction
  • Introduced the CDN
  • NPM install

The following is based on [email protected]

Vue instance

Vue instances are objects created through Vue() and are the basis for using Vue functionality. The arguments to Vue() are configuration objects, as described below.

El option # 5

Use to select a DOM element (not HTML or body) as the mount target for the Vue instance. It can be a DOM element variable or a CSS selector string.

Only mount elements inside are processed by Vue, and normal HTML elements outside. It represents the View layer in MVVM.

After mounting, call: vuemodel.$el

Vuemodel.$mount()

Interpolation {{}} #6

Interpolation expressions can only be written inside element content, and only JavaScript expressions (callable functions) can be written inside.

Its values are dynamically generated for easy maintenance.

Data option # 7

Data Objects store data needed by vUE instances.

Data can be directly invoked by the instance, for example, vuemodel.$data.data1 = vuemodel.data1

It can also be accessed directly from the view through interpolation expressions such as

{{data1}}

, and they are bidirectional bindings.

Views cannot be automatically updated by array type values in data, index operations (e.g., changing the value of an item), or length operations (e.g., length=0, emptyarray). Other array methods are normal. Vue. Set (data.arr, index, newValue) allows binding rendering.

The methods option # 8

Methods Objects store functions that need to be used in vUE instances.

e.g.

methods: {
    fn (value) {
        return value * 2}}Copy the code

Methods can be used in interpolation expressions, such as {{fn(dataA)}}

It can also be called by an instance, such as vuemodel.fn(), where this points to the instance for easy access to data and other methods under the instance.

T2: vue.js basic instruction

The instructions are written inside the start tag, which is essentially an HTML custom attribute. The vue.js directive begins with a V -.

Content processing instruction

V – once order # 2

Make the interpolation inside the element work only once, that is, after the data is first fetched and rendered to the view, it does not change with the data.

V # 3 – text instructions

Replaces the entire element content with specified plain text data, such as

, which is the data in data that drives the view.

Assignments are displayed in plain text and do not parse HTML structures.

V – HTML order # 4

The HTML in the value is parsed.

The attribute binding directive V-bind

1

, v-bind can be omitted.

Binding property values can be variables, expressions.

2

attrObj is an object whose key-value pairs are properties and values. At this point, v-bind exists as a custom attribute.

Binding #7 for the class attribute

Use: Class bound attributes do not affect native class attributes and can coexist.

Control when binding multiple class names: :class=”{a: true, b: false, ‘class-c’: true}”. Object key-value pair, K is the class name, V is a Boolean value, controlling whether the class name is valid.

Class =”[a, {b: true, c: false}, d]” Arrays, whose members can be objects.

Binding #8 for the style property

The :style binding value is an object. Similar to CSS, but with the values enclosed in quotes, properties with – are either humped or enclosed in quotes.

Styles with the same name, :style will override the native style.

Bind multiple style objects: :style=”[baseStyle, styleObj]”, using an array of objects. Member objects are automatically fused, usually for base and special styles, and are easy to reuse and maintain.

Rendering instructions

V – # 10 for instructions

For traversing data rendering structures, arrays and objects can be traversed.

Array: < li v – for = “(item, index) in arr” > {{item}} < / li >

  • {{value}}
  • When using V-for, you should always specify a unique key attribute to improve rendering performance and avoid problems (data changes while rendering is lazy, leading to confusion). The key value can come from the ID attribute of each item in the array.

    You can also generate multiple elements with v-for:

  • {{item}}
  • When repeated generation of multiple elements is required, you can use V-for for the virtual element

    V – show order # 11

    It is used to control the display and hide of elements. It is suitable for frequent switching between show and hide.

    V-show is an attribute provided by vUE. Elements are displayed when the value is true and hidden when the value is false.

    (Does not apply to virtual elements, such as template)

    V – if order # 12

    Use to control the creation and removal of elements based on conditions.

    <p v-if="false"> Condition is false, element will not be created. </p><p v-else-if="true">If the condition is true, the element is created.</p>
    <p v-else>No else is entered, the element is not created.</p>
    Copy the code

    【 note 】

    • Elements of the same type that use V-if also need to bind different keys
    • You should avoid applying v-if to the same tag as V-for, as this may result in wasted performance. V-if is usually used on the parent element before traversal element generation.

    T3: Event and form processing

    The event binding directive V-ON

    Form input binding directives V-model #2 to 6

    Use to set two-way data binding for input class form elements such as <input>, <textarea>, and < SELECT >.

    Radio buttons

    Check box

    • Single option (scenarios that can be checked and unchecked, such as agreement)

      The bound data is initialized to an empty string. If checked, you get true, and if unchecked, you get false

    • Multiple options

      The bound data is initialized to an empty array, and when checked, its value is pushed into the array.

    Select box < select >

    • Single topic selection

      [Common] Add an option whose value is empty. If no option is selected, it is selected by default.

    • Multiple choice

    Modifier of the vue directive

    Can be used after the V-ON instruction to connect

    Event modifier

    .prevent

    PreventDefault event behavior, equivalent to event.preventdefault ()

    .stop

    Prevent event propagation (bubble), equivalent to event.stopPropagation()

    Used on child elements to prevent upward bubbling.

    .once

    Used to set the event to fire only once

    Modifiers can be conjoined

    Key modifier (only for keyboard events)

    The key code

    The deprecated KeyCode can still be used as a KeyCode, but the alias provided by Vue is preferred.

    • .enter
    • .tab
    • .delete(Capture delete and Backspace keys)
    • .esc
    • .space
    • .up
    • .down
    • .left
    • .right

    When used continuously, any key can trigger an event, that is, an or relationship.

    System modifier

    • .ctrl
    • .alt
    • .shift
    • .meta

    When used consecutively, the system modifier means a shortcut key, that is, it must be used together.

    .exact

    Used in events that require only precise system modifiers to trigger.

    Mouse modifier

    • .left
    • .right
    • .middle

    Modifier of the V-model directive

    V-model is used for bidirectional data binding of form elements, see #2~6.

    .trim

    Automatically filters Spaces at the beginning and end of user input.

    .lazy

    Change the v-Model firing mode from an input event to a change event

    .number

    Automatically converts a value entered by the user to a numeric type using parseFloat(), or returns the original content if it cannot be converted

    T4: Advanced syntax

    Custom instruction

    Add built-in instructions to meet the needs of customization.

    Custom global directive #2

    Vue.directive('focus', {
        inserted: function (el, binding) {
            el.focus()
        }
    })
    Copy the code

    Used before the instance is generated. The directive v-focus, defined in the example above, can be used to get the focus of a page, such as a search box.

    Inserted is a hook function that is called when the element is inserted into its parent node. Other hook functions can be used as required.

    The hook function takes the following arguments:

    • El: selected element

    • Binding: Detailed setting of the directive

      • -Leonard: So, that’s a modifiers
      • Expression: Expression of the vue attribute value
      • Value: The value of the attribute, or the computed result of expression

    Custom local directive #3

    Directives that can only be used within the current Vue instance or component.

    Inside the argument to the Vue constructor:

    directives: {
        focus: { inserted (el) { el.focus(); }}}Copy the code

    The filter

    Filters can be used in interpolation expressions and in the value of the V-bind binding attribute

    Content and filter to | pipe connection

    Global filters #4 to 5

    Before generating the Vue instance, set the filter.

    Vue.filter('filterA'.function () {})Copy the code

    Filter function parameters:

    • Value: The value received for processing, always the first parameter.

    The return value of the filter function is replaced with the original value

    Multiple filters can be used consecutively.

    Local filter #6

    Can only be used in the current instance. Inside the argument to the Vue constructor:

    filters: {
        
    }
    Copy the code

    If a local filter has the same name as a global filter, the local filter takes effect.

    【 Common 】 Defines a global filter. Redefines a local filter with the same name where special requirements are met.

    Compute properties computed #7

    Complex functional code is not recommended in the view section

    The calculation attribute is used in the form of attribute, and the corresponding function is automatically executed when accessing

    The computed: {}Copy the code

    Differences between Methods and computed Tomography:

    • Computed has a cache type, whereas Methods does not.

    • Computed is accessed by attribute name, and methods needs to be called.

    • Computed applies only to computing operations that compute the same value twice.

    setter

    Evaluate properties by default using only getters, getResult as a method; When setters are needed, getResult is an object that contains both get() and set() methods.

    The listener # 10 ~ 11

    data: {
        value: []}watch: {
        value (val, oldVal) {}
    }
    Copy the code

    The listener is written inside the Watch object and is the function of the same name in data to listen for the data member.

    Listening to the object
    data: {
        obj: {
            content1: 'c1'.content2: 'c2'}},watch: {
        obj: {
            deep: true.// The deep switch is used to listen for changes in object members, not arrays.
            handler (val) {}	// We can only get the new value val when we listen on objects or arrays}}Copy the code
    Listening to the array

    Listen on arrays without turning on deep.

    You cannot listen for changes in array length or changes using indexes, only changes made by array methods or vue.set ().

    Vue DevTools #12

    This is used when the web page uses vue.js

    Vue instance lifecycle #13

    Lifecycle hook functions:

    1. Create phase (only once per instance)

      • BeforeCreate: called before instance initialization.
      • Created: called after an instance is created.
      • BeforeMount: called before the instance is mounted.
      • Mounted: Indicates that an instance is mounted
    2. Run phase (call on demand)

      • BeforeUpdate: Called after data is updated before view is updated.
      • Updated: Invoked after the view is updated.
    3. Destruction phase (only once per instance)

      • BeforeDestroy: Called before instance destruction.
      • Destroyed: Called after the instance is destroyed.

    T5: Comprehensive case of Todomvc project

    The preparatory work