What has the agent solved for me

During the development of a project, almost all interfaces need to know its return status, such as failure or success. On the mobile side, results are usually returned in the background, and we only need a popover to display the results. But if you had to manually define each popover in the entire project, that would be a huge amount of code, and very difficult to maintain. The usual approach is to bind a public method to the prototype, such as this.message(‘ background returns interface information ‘). It looks like it saves a lot of effort but it’s still a lot of trouble. If you use a proxy to do a global proxy, then it’s a completely different story. Any API will pass state to the broker, and the broker will react directly to the result.

import Vue from 'vue'
import {ToastPlugin} from 'vux'
import api from './api/api'Use (ToastPlugin); use(ToastPlugin); use(ToastPlugin); / / toast initializationletvm = new Vue(); // Create an instance because toast popover depends on it so create an instance here to call popover with vue.prototype. dilog =function (value) {
  vm.$vux.toast.show({
    text: value || "Business processed successfully".type: 'text',
    width: "5rem",
    position: 'middle'}); }; Var interceptor = {interceptor = {set: function(recObj, key, value) { vm.dilog(value); // Popup layer, value is the status value returned by the APIreturnthis } }; Var proxyEngineer = new Proxy(API, interceptor); Vue.prototype.api = proxyEngineer; // Replace the API with a new instanceCopy the code

The reason for doing this is that it is not necessary to import a VUE instance in the API file that has been created. It would be costly to import vue directly into the API file without using a proxy.

class API {
  constructor(){
    this.massages = "Business processing successful!"; // The current interface error message this.code='000000'||'999999'
  }

  post(params, callback, dailog, errcallback = function() {// Error message callback}) {//dailog is whether to initialize a popover, such as a list usually does not need to be loaded to pop up a success, or get data success etc. Boolean, usually used only when clicking on an event, or when initial /// data is reported in error. //this.code stands for status codelet config={};
    config.data = params.data||{};
    var url = `${base}${params.url}.do`; var dailog = dailog; // Encapsulates the AXIos post methodreturn axios.post(url, config.data, config, dailog).then(res => {
      let rst = res.data;
      if (rst.code === '000000' || rst.code === '999999') {
        callback&&callback(rst.result||{});
        ifMassages = rst.message; (dailog) {this.massages = rst.message; }}else{ errcallback && errcallback(); this.massages=rst.message; } // If this is returned, the proxy object's this is returnedreturn res
    }).catch(e => {
      console.log(e)
    })
  }

}
const api = new API();

exportThe core of the default API // code is to define the information field on the class, and feedback the information by changing the massages valueCopy the code

This.api. post(params, res => {// You need to execute the logic // no more need to write //this.$msg(res.value), the agent has already handled it for you})Copy the code

This is the proxy I use in practice, and it works on both multiple and single pages. Of course, the code is a little rough, and there are no restrictions, just the idea. In case I forget. By the way, I’m going to take a page from Understanding ECMAScript 6 and add a little bit of my own Understanding to the proxy feature. Just take notes.

What are agents and reflections?

By calling new Proxy(), you create a Proxy to replace another object (called a target). This Proxy virtualizes the target object so that the Proxy and the target object can be treated ostensibly as the same object. Proxies allow you to intercept low-level operations on target objects, which is the internal capability of the JS engine. Interception uses a function (called a trap) that responds to a particular operation. The concept of interceptors is important. The Reflect interceptor has some reflection interfaces,

Create a simple proxy

let target = {};
let proxy = new Proxy(target, {});
proxy.name = "proxy";
console.log(proxy.name); // "proxy"
console.log(target.name); // "proxy"
target.name = "target";
console.log(proxy.name); // "target"
console.log(target.name); // "target"Proxy intercepts the targetCopy the code

I’m mainly using points

let target = {
name: "target"
};
let proxy = new Proxy(target, {
set(trapTarget, key, value, receiver) {// Ignore existing attributes to avoid affecting themif (!trapTarget.hasOwnProperty(key)) {
if (isNaN(value)) {
throw new TypeError("Property must be a number."); }} // Add attributesreturn Reflect.set(trapTarget, key, value, receiver); }}); // Add a new attribute proxy.count = 1; console.log(proxy.count); // 1 console.log(target.count); // 1 // You can assign a non-numeric value to name because the property already exists proxy.name ="proxy";
console.log(proxy.name); // "proxy"
console.log(target.name); // "proxy"// Throw an error proxy.anotherName ="proxy";
Copy the code

In addition, vue3.0’s responsiveness is also used as a proxy