Your location:Tech News>News>Script>15 minutes to master vue-next-responsive principles

Latest News

15 minutes to master vue-next-responsive principles

Author:fsadmin

Views:

  EDITORIAL

  The latest vue-next source code released, although the pre-alpha version, but this time is a better time to actually read the source code.In vue, the more important thing of course several of its response systems, in previous versions, have been responsive principle and a number of its articles were introduced, not go into here.In vue-next, the implementation principle is still the same and before that by the observer mode and data hijacking, but its implementation has been changed.

  For analytical articles principle, I personally prefer the kind of "white" style article, that is not a particularly large excerpt of the code, do not set forth some very esoteric principles and concepts.When I was new to react, remember there is a use jquery to introduce react articles, from simple to complex, all-embracing knowledge points behind I set out to learn react later played a lot of help.

  Therefore, this article I intend to write about in this style to take advantage of recent spare time to read some of the ideas and experience vue-next-responsive module source code, be initiate, while achieving a minimalist response systems.

  If wrong, correct me hope yet.

  Preliminaries

  Whether reading this article, or read vue-next source responsive module, the first two points are essential knowledge:

  Proxy: es6 new class of agents built-in tools

  Reflect: es6 new reflection tools

  Due to limited space, not repeat them in detail here, these two classes of use and use of the recommended three I think a good article for reference:

  ES6 Proxies in Depth

  ES6 Proxy Traps in Depth

  ES6 Reflection in Depth

  interface

  For RFC vue-next-responsive systems, can be found here.Although the distance for some time now, but by reading the source code, you can find some shadow.

  We generally results to be achieved as shown in the following code:

  // implement two methods reactive and effect

  const state = reactive ({

  count: 0

  })

  effect (() => {

  console.log ( ''count:'', state.count)

  })

  state.count ++ // Input count: 1

  We can find the familiar rely collection phase (also observer mode subscription process), is carried out in effect, depending preparations collected (that is, data hijacking logic), is carried out in reactive, whereas the data change triggers the logic state in response to the back.When carried count ++ code execution (also the observer pattern release process), incoming internal effect until after the callback function will execute and enter count: 1.

  Types and public variables

  Since vue-next has been rewritten by ts, ts here I can use to achieve this minimalist version of the response systems.Mainly related to the type and public variables are as follows:

  type Effect = Function;

  type EffectMap = Map;

  let currentEffect: Effect;

  const effectMap: EffectMap = new Map ();

  currentEffect: currently being used to store collected dependent effect

  effectMap: Each key represents the target object corresponding to the array depends on its effect, it may be appreciated that as the observer subscribers dictionary mode

  Proxy use for data hijacking

  In previous versions, vue use Object.The setter and getter defineProperty to hijack data objects, vue-next through Proxy.As we all know, Object.Data hijacking defineProperty realized there is a certain limit, but will be much stronger Proxy.

  First of all, we are in the back of the head, imagine how you can use Proxy to hijack it for data?Very simple, as shown in the following general structure:

  export function reactive (obj) {

  const proxied = new Proxy (obj, handlers);

  return proxied;

  }

  handlers Here is a statement of how the processing logic of each trap, such as:

  const handlers = {

  get: function (target, key, receiver) {

  .

  },

  set: function (target, key, value, receiver) {

  .

  },

  deleteProperty (target, key) {

  .

  }

  // .And other trap

  }

  Because here is a minimalist version of realization, then we can only achieve get and set two trap on it, corresponding to rely on collection of logic and trigger a response.

  Reliance collection

  For implementation relies collection, as is the minimalist version, to achieve the following premise:

  Do not consider nested objects

  Irrespective of the type of collection

  Irrespective of the type of foundation

  Without regard to the processing of the proxy object

  Haha, after the basic rule out these four points, this function will depend on collecting very thin and light, as follows:

  function (target, key: string, receiver) {

  // only be collected within a certain effect dependence

  if (currentEffect) {

  if (effectMap.has (key)) {

  const effects = effectMap.get (key);

  if (effects.indexOf (currentEffect) === - 1) {

  effects.push (currentEffect);

  }

  } Else {

  effectMap.set (key, [currentEffect]);

  }

  }

  return Reflect.get (target, key, receiver);

  }

  Logic implementation is very simple, in fact, the Observer pattern registered subscribers to realize the logic, it is worth noting that this logical target for the assignment, we entrust to Reflect to complete, although the target [key] also work, but using Reflect is a way to promote more.

  Trigger a response

  Trigger logic in response to the relatively simple, in fact, correspond to the observer mode, logic publishing events, as follows:

  function (target, key: string, value, receiver) {

  const result = Reflect.set (target, key, value, receiver);

  if (effectMap.has (key)) {

  effectMap.get (key).forEach (effect => effect ());

  }

  return result;

  }

  Here again, the use of Reflect to assignment of the target, as it will return a boolean value represents success, but also need to set the trap value represents the same meaning.

  To initialize the proxy object by reactive method

  After the agent to achieve the logical data hijacking, we need only reactive in this process, a proxy object instance returns to substantially the code frame is also referred to our above prior pops achieve it?

  as follows:

  export function reactive (obj: any) {

  const proxied = new Proxy (obj, {

  get: function (target, key: string, receiver) {

  if (currentEffect) {

  if (effectMap.has (key)) {

  const effects = effectMap.get (key);

  if (effects.indexOf (currentEffect) === - 1) {

  effects.push (currentEffect);

  }

  } Else {

  effectMap.set (key, [currentEffect]);

  }

  }

  return Reflect.get (target, key, receiver);

  },

  set: function (target, key: string, value, receiver) {

  const result = Reflect.set (target, key, value, receiver);

  if (effectMap.has (key)) {

  effectMap.get (key).forEach (effect => effect ());

  }

  return result;

  }

  });

  return proxied;

  }

  Preparations rely collected

  Mentioned above, the dependence of the collection work, we performed conditionally, i.e., the effect in one, we will collect, the logic value of the other, we will not be dependent on the collection, thus, effect in order to achieve this method formally exist, as follows:

  export function effect (fn: Function) {

  const effected = function () {

  fn ();

  };

  currentEffect = effected;

  effected ();

  currentEffect = undefined;

  return effected;

  }

  The reason is so simple to achieve, because we are here in a minimalist version, no need to consider factors such as readOnly, and other anomalies as well as the timing of collection.Can be found, is to pass the callback function wrapped in another method, and then use this method staging currentEffect this variable, you can then try to run it.When the effect has finished running, then currentEffect blanking, so that you can achieve only dependent collected under effect.

  running result

  I wrote a simple codepen on a counter demo, linked below:

  https: // codepen.io / littlelyon1 / pen / mddVPgo

  Written in the last

  The minimalist response systems, although can be used, but there are not many factors to consider, in fact, the above is a prerequisite for those of us ignore, here, and then list what, and gives solution source code:

  Processing the underlying data types: basic data types may be encapsulated as a ref object whose value points to a value of basic data type

  Nested objects: a recursive process can be executed proxy

  A collection of objects: the preparation of a special trap processing logic

  Acting Example: cache the proxy instance, can be returned directly to the next encounter

  But I still recommend you go directly to read the source code, because you will find in this minimalist version of the source code will be based on the use of more complex data structures and processes to control and trigger processes rely collect responses, and a variety of special circumstances there are also more detailed consideration.

  In addition, this is just a simple realization vue-next response systems, and other functional modules such as, for example, instruction, template parsing, vdom, etc., I am ready to take advantage of the recent free time to go and see, if you have time, recently sorted out share for everyone.

  That''s all for this article, I want to be helpful to learn, I hope you will support script Home.

  You may also be interested in the article: vue data responsive principles of knowledge summary Vue3.0 Detailed data responsive principle by drawing takes you in-depth understanding of vue Vue Responsive Responsive principle principle Observer, Dep, Watcher On Vue understanding of the principles of responsive vue.js responsive analysis and implementation principles detailed analysis vue responsive principle

Recommend article

Relate article