Front-end interview preparation --- Vue papers

This article from the below review several aspects Vue knowledge:
1. MVC && MVVM  
2. 数据双向绑定
3. Vue的生命周期
4. 虚拟dom的实现原理
5. vue-router
6. Proxy
7. vuex复制代码

MVC && MVVM

M - model layer, representing the data model
V - view layer, representing the view layer, the UI display
C - control layer, the control layer, the processing complex business logic
VM-- viewModel layer, and a synchronized view of the object model, in fact, can be understood as a two-way data binding
Vue is a framework for MVVM pattern

v-show, realization of the principle of v-if

v-show is false, and display is provided by js none; is true, setting display: ''; To make such a display property setting js failure.

v-if dom elements are added or deleted by js manually.

Communication between components

Communication between components in total are classified as follows:

1, a parent -> child:

The parent element passed in a format attribute, attribute child elements receiving props;

// 父元素
<editor :name='data'></editor>

// 子元素
props: {
    name: {
        type: Object,
        defalut: function(){
        
        }
    }
}

复制代码

2, child -> parent:

In the event a parent component binding, since the components starting with $ emit events

3, Brothers components:

4, when relatively deep nested components: vuex

Vue two-way data binding

The so-called two-way data binding refers to the view layer and data layer influence each other, such as the input frame data input, the data corresponding to the stored changes; when storing data to a data re-assignment, also becomes the value input box.
Two-way data binding mainly through the release of data hijacking + subscribers mode, hijack each attribute set and get, release time changes in data to subscribers, triggers the corresponding callback.
Really rely on this property is Object.defineProperty
When it comes to this principle, you can take a look publish - subscribe pattern.
  • Publish - subscribe pattern:

I began to have a little understanding of this model, but to see this article in a metaphor instantly understand.
In fact, this subscription model just like we usually publish a common mode of public micro-channel subscription number is the same.
  1. Publish the entire subscription model as a platform, allowing users to subscribe to and publish operations can occur, it is similar to micro-channel public platform number
  2. Subscribers can subscribe to multiple operations, just as we can subscribe to multiple public the same number, but need to provide a platform for us to subscribe to the name, as well as some information about their subscribers.
  3. As a publisher, in fact, like a public number, he does not care who the specific subscriber is subscribed to as long as the user will receive information dissemination. We need to tell the whole publishing operation platform, which requires public release number, release any information.
  4. Subscribers can also cancel a subscription, you will need to know the platform, launched unsubscribe users which is, what is the name of the public as well as cancellation of No. Yes.
So a simple publish-subscribe pattern is formed, below man of few words said, directly on the code:
const SubPub = function() {
    // 用Object格式,可以通过value存储订阅者的一些信息
    // 订阅器 --- 类似于微信公众号这个平台,每一个元素类似于一个公众号,key值为公众号的名字,value值记录订阅公众号的人;
    this._observer = {};
}

SubPub.prototype = {
    // 订阅函数,需要提供我要订阅的公众号名称,以及自己的姓名
    subscribe: function(type, callback) {
        const self = this;
        if(Type(callback) !== 'function') return;
        if(!self._observer[type]) this._observer[type] = []
        this._observer[type].push(callback);
        return self;
    },
    // 发布函数,需要提供哪个公众号需要发布信息,以及发布的内容;
    publish: function() {
        const self = this;
        const type = Array.prototype.shift.call(arguments); // 因为arguments不是数组,是一种类数组类型,所以没有shift、slice这些方法
        //发布的内容
        const theme = Array.prototype.slice.call(arguments);
        const subs  = self._observer[type];
        if(!subs || !subs.length) return;

        subs.forEach(sub => {
            sub.apply(self, theme);
        });
        return this;
    },
    // 取消订阅,需要提供取消公众号的名字,和发起该取消操作的用户
    removeSub: function(type, callback) {
        const _subs = this._observer[type];
        if(!_subs || !_subs.length) return;
        _subs.map((item, index) => {
            if(item === callback) {
                _subs.splice(index, 1);
            }
        })
        
        return this;
    }
}

function Type(value) {
    return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}

// 实例一个发布订阅器
let sp = new SubPub();
// 定义订阅者
const sub1 = function(data) {
    console.log('sub1' + data);
}

const sub2 = function(data) {
    console.log('sub2' + data);
}

const sub3 = function(data) {
    console.log('sub3' + data);
}
// 发起订阅操作
sp.subscribe('click', sub1);
sp.subscribe('input',sub1);
sp.subscribe('qqq',sub1);

sp.subscribe('click', sub2);

sp.subscribe('input', sub3);

// 开启发布
sp.publish('click', '第一次发布click事件');
sp.publish('input', '第一次发布input事件');

sp.removeSub('click', sub1).publish('click', '第二次发布click事件');复制代码
  • Object.defineProperty to use

Next, look at the use of Object.defineProperty.
let obj = {};
let song = '七里香';
obj.singer = 'JayZhou';
Object.defineProperty(obj, 'music', {
    configurable: true, // 可以配置对象, 为true的时候才可以删除属性
    enumerable: false, // 是否可枚举
    get () {
        return song;
    },
    set (val) {
        song = val;
    }
});

console.log(obj.music); // {singer: '周杰伦', music: '七里香'}

obj.music = '听妈妈的话';
console.log(obj.music);

delete obj.music
console.log(obj);

for(var i in obj) {
    console.log(i); // 只有singer 因为music是不可枚举的
}复制代码
Disadvantages:
  1. You can not monitor an array of changes

Vue realization of the principle of MVVM pattern:

  1. observe: a data listener, all the attributes of data objects, including sub-attributes listen, if changed, to get the latest value and notify subscribers
  2. compile: a parser instruction, scanning and parsing instruction node for each element, the replacement data according to an instruction template, and the corresponding binding function
  3. watcher: a subscriber, it will act as a bridge between the listener and the instruction data parser. To subscribe to data changes each attribute data change notification is received, the callback function to update the UI page
  4. Mvvm entry function, the integration of the three

Vue life cycle

vue life cycle is created from -> Mount -> Update - Process> destruction.

Total is divided into eight steps:

beforeCreate, created,
beforeMount, mounted,
beforeUpdate, updated,
beforeDestroy, destroyed

Vue virtual DOM

The so-called virtual DOM, is a JS object that is used to store the DOM tree structure.
process:
  1. Create a dom tree
  2. Diff comparison algorithm using the stored difference patches object side is pressed four formats
  • Node Type change
  • Properties changed
  • Text change
  • Add / move / delete sub-node
3. rendering differences
  • Traversing patches, the node needs to be modified to take out
  • Local updating dom, operated using document.fragments dom, one-time update for the browser.

document.fragment:

It is not the main part of the DOM tree of DOM node.
Normally used to create a document fragment, fragment additional elements to the document, then the document fragment attached to the DOM tree. Because of document fragments in memory, not in the DOM tree, so a child element inserted when reflux does not cause the browser, so better performance

nextTick

Dom for a callback after rendering, the new version is the default microtasks

vue-router

Mode: hash, History
Jump method:
  1. this.$router.push()
  2. <router-link to=''></router-link>
  3. this.$router.replace()
Placeholder:
<router-view></router-view>

The default is to hash mode, history need background configuration, utilization, monitor change change Html5 the History API implementation.

router and route difference:

$ router: is an instance VueRouter, it is a global object, the main achievement of the jump using the route. Commonly used router.push () and router.replace () method.
push method adds a new record as the browser's history stack.
replace alternate route, no history.
route: a routing information object, each router has a route object is a local object. You can get name, query, params, path and other parameters.

Proxy

Definition: From MDN defined: to customize the behavior of the definition of basic operations (such as: property search, evaluation, enumerations, function calls, etc.);
In addition Ruan Yifeng relatively easy to understand explanation of: erecting one interception before the target object, the object outside access to the object, this layer must first pass interception, thus providing a mechanism to filter access to the outside world and rewrite .

grammar:

let p = new Proxy(target, handler);复制代码
A simple example:
var proxy = new Proxy({}, {
    get: function(target, key, receiver) {
        console.log(`get ${key}`);
        return Reflect.get(target, key, receiver);
    },
    set: function(target, key, value, receiver) {
        console.log(`set ${key}`);
        return Reflect.set(target, key, value, receiver);
    }
});

proxy.name = 'jack'; 
// set name
console.log(proxy.name);
// get name
// jack复制代码
The above example is an empty object has been intercepted.
Vue3.0 Proxy in use instead of defineProperty. Whether it is far stronger than the proxy defineProperty operations on or from the underlying functionality.

advantage:

  1. Can monitor changes in the array, this is impossible defineProperty
  2. Direct the listener object, not the object of the property, and will generate a new object

Vuex

  • What is Vuex?

Vuex vue state management tool is used to store all the components of the state set, and a corresponding state rules to ensure a predictable manner changes
  • Vuex core attributes:

Vuex has five core attributes: state, getter, mutation, action, module
  1. State: storing a data state; can be accessed through this $ store.state; in the Data corresponding to vue; manner of storage of data is responsive to, vue component can read data from the store, if the data corresponding change component also occurs. updates.
  2. Getter: the equivalent of computing property store, and his return values ​​are cached according to his dependence, and only when it is dependent on a change of will be recalculated.
  3. Mutation: The only way to change vuex the store is submit mutation
  4. Action: contain any asynchronous operation, changes state indirectly by submitting mutation.
  5. Module: The store is divided into modules, each module includes a top four methods, even submodule
  • vuex data transfer process

  1. When the component data modifications, dispatch calls to trigger action inside method;
  2. Each action has inside a commit method may be modified by mutations inside commit data modification method
  3. a mutation will have a state parameter, so that the state data can be modified through the mutation
  4. After data modification, change page
  • Why vuex?

  1. When the components when nested, parent-child component data transfer is troublesome.
  2. Increase readability and maintainability of the code
  3. Data are responsive reduce data distribution operation;



Reproduced in: https: //juejin.im/post/5d02016c6fb9a07ec27b9e50

Guess you like

Origin blog.csdn.net/weixin_33739523/article/details/93169754