Flexible Vue

1. An efficient tracking mechanism

Vue tracks data changes by defining data access descriptors (set and GET) via Object.defineProperty.

When the Vue component is initialized, properties under Data are added to set and GET in a loop until all descendant properties have been added. When the value of one of the properties of Data changes (execute set), it issues a notification to the component that subscribed to the data to update the component.

In a set, a component can subscribe to notifications of changes to that data.

Set and GET are called access descriptors of objects, and the corresponding access descriptors are called data descriptors. The two cannot coexist and, by default, are data descriptors. As follows:

React uses comparison references to track changes in data. When setState is set, React directly replaces the old state with the new state.

As shown below, each time handleClick is executed, the component is re-rendered even if the value of the data is not changed (but the reference address is changed). This rendering is unnecessary.

React and Vue both use the vDOM diff algorithm to update components when notified of data changes. Vue is more efficient than React at tracking data changes.

2. The Embarrassing V-Model

Vue cannot detect changes in object attributes or changes in array index length. When defining data of object type, the following attributes are generally defined. However, JS is a dynamic language, it can not define objects in advance, and arbitrarily manipulate object properties. When used in conjunction with v-Model, the attributes of object data can also be used without pre-definition.

For example, in form-based components, a common behavior is not to define properties such as title and type for formData. The V-Model will automatically respond to user input and add properties to the formData.

<template>
    <div>
        <input v-model="formData.title" placeholder="Please enter a title" />
        <select v-model="formData.type">
            <option value="1"> Category </option> </select> </div> </template>data() {
    return {
        formData: {}
    }
}
Copy the code

Props is a way for components to communicate data from top to bottom. If a child component modifs its props in reverse order, Vue warns that it should avoid operating directly on props and use a data or computed property instead, and that the modified value is not passed to the parent component.

However, with the help of the V-Model, props of type object can also be passed from a child component to a parent component. The props value of the simple type still cannot be modified.

When the V-Model internally detects that the key is bound to the object (indexOf(‘.’) > 0), it calls the set method, updates the property to the object, and adds a subscription event to the component.

Vue1.0 uses two-way data binding, while Vue2.0 uses one-way data flow, that is, only parent communicates with child, and the child communicates with parent in the way of callback function. Vue3.0 was unable to detect changes in data attributes. Vue.prototype.$set and json.parse (json.stringify) were used to correct this. In the future, Vue3.0 will use proxy instead of Object.defineProperty to listen for data changes. Proxy will listen for objects directly, not properties, and it can detect changes in arrays and objects.

3. Scope issues

JS development has three major difficulties, prototype, closure and scope. With the help of the ES6 Module, the number of potholes for stereotypes and closures has been reduced, leaving scopes as the most commonly encountered potholes.

In React, adding events to components requires modifying the execution scope of functions. As follows, onClick is defined in the global scope, and its this is undefined. Because JS is a statically scoped language, its scope is defined at definition time. Here, to get the state inside the React component instance, all bind functions are scoped to the component instance.

Vue encapsulates CSS in a manner similar to shadow DOM. After scoped property is added, CSS is only used within components and the CSS between components does not affect each other.

React uses CSS in JS, CSS Module, and style-component to encapsulate CSS, none of which is as useful as Vue.

React CSS in JS

4. Flexibility of Vue

Compared with React, Vue has the highest degree of compatibility with JS. It has no class-based data flow management and no slash-and-burn JS writing method.

Vue’s tracking data mechanism, V-Model bidirectional binding, and JS/CSS scopes all cleverly take advantage of JS as a dynamic language. This makes Vue a very easy-to-use technical framework that has a place in fast-paced, frequently iterative development needs. I developed and maintained a total of 9 projects in commercial Products over a year, including 1 React, 1 Angular and 7 VUE projects. Vue is very easy to use, some simple needs, let the backend students take care of.

It has long been argued that Vue is suitable for small projects and React is suitable for large projects. In the past, Vue was criticized for its data flow management. In fact, now Vue2 is not much different from React, and Vue is even better than React thanks to V-Model and Vuex. Vue3 will be written in Typescript and build projects will be more robust.

Two. Five data flow management modes

1. Props + emit callback

React and VUE are both used for component communication. Simple and simple.

Dependency component parent-child relationships.

If the parent component is found to have subscribed to the events of the child component during instantiation, the subscribed events will be added to the events list, allowing the developer to publish events, i.e. $emit events.

2. props + eventBus

Applies to all components, independent of nested relationships between components.

In EventBus, instantiate a Vue instance as an observer and all components as subscribers.

// EventBus.js
import Vue from 'vue';

export default new Vue();
Copy the code
// Add subscriber eventBus.$on('reset-preview', this.closeHandler); // Publish the notification eventBus.$emit('preview');
Copy the code

Vue implements both on and EMIT methods internally. The ON method adds subscribers to the queue and emit sends notifications to subscribers when events change.

EventBus does not rely on component nesting, but the data flow is arbitrary and difficult to support for complex business requirements. So you need a centralized observer, observing changes in data, top-down components responding to changes in data, bottom-up updates of changes in data to the observer center.

What is the difference between emit callback and eventBus?

The EMIT callback emphasizes the component relationship, where the parent component is the subscriber and the child component is the publisher. EventBus doesn’t care about component relationships; one instance of an eventBus instantiation is a publisher, and components are subscribers.

3. vuex

Advantages:

  1. Solve the problem of nested data flows for all grandparent and parent-child components
  2. Cache data to reduce the number of HTTP requests
  3. One-way data flow makes the data flow clearer
  4. Reduce the functions of props and callbacks to decouple components

Points to be aware of when using VUex

  1. Data with strong background constraints should not be written in VUEX.

Vuex, like VUE, tracks data changes by hijacking setters and getters, so vuex cannot detect additions and deletions of arrays and objects.

For example, form-based data needs to be submitted to the background by adding fields. Vuex cannot add or delete attributes, $store.mit to store, store data is not updated.

  1. At the end of the data life cycle, clear the store cache of data.

For example, a complex type of data is requested from the server and stored in VUEX, passed between components, and then submitted to the server after the data processing is complete. At this point, you should clear the vuex data so that the next time you open the page, the data in vuex is clean.

In general, the VUEX cache is checked during the Component’s Created life cycle, and if no cache exists, the data is pulled again. Reset the store to clear the data cache before the end of the component’s life cycle.

When is vuex appropriate?

  1. When you need to cache data
  2. Emit can’t be solved at all

Use Redux only when React really doesn’t work. — — — — — — — — story writer

Overuse of VUex can lead to bloated projects and increased coupling between components.

4. route

Traditional, suitable for data transfer between pages. For some requirements that need to paste urls for others to access, the required parameters need to be added to the Router instead of the VUex.

Such as filter list page, media traffic bucket management page. This page structure is the same, and the variety is numerous. Can not be divided into multiple pages, but also need a separate page display effect, suitable for storing data in route.

When using router to send parameters, note the following:

  1. Component lifecycle hooks (ensure required route parameters) 1.1 For pages that rely on the Router to store data, note that in the vUE component lifecycle hooks, the order in which the parent and child components are verified is Father created – > child created – > child mounted – > father mounted, so check the route in the created life cycle parameters, ensure that the component render correct data shows in the future.

5. Component instance method invocation

For nested form-based components

For example, when creating a parent task, a child task can be added to the parent task form at the same time, and the child thinks that different task reward rules can be added respectively. For example, when creating orders, you can add advertising groups, advertising plans, advertising ideas, advertising ideas can add various materials. These nested complex form-based components are better suited for this.

Iii. Principle of component separation

1. Make good use of slot and open/close rules.

Modify closed, expand open.

2. Functional separation, single responsibility rule

Functional component or UI component? Simplified use. For example, when pagnition handles total < 1, it does not display pagers such as filter list components, keeps the UI part, and slot the submit button into functional components such as upload components

3. Know the principles at least

As few external dependencies as possible on function points within components and as few external dependencies as possible. The simpler the better. The pinnacle of reference design, the Kiss rule.

Four. Some matters needing attention

1. Use $next to get the component’s rendered DOM

2. V – for the key

3. Overriding complex types of props

4. Ajax encapsulation

Create instances of AXIos that encapsulate Ajax and reduce the amount of code handling callbacks. Modifying axios’ interceptors directly would pollute the entire project ajax call rules. For files that are imported multiple times, WebPack packs only once.