SoFunction
Updated on 2025-04-06

Example of Vue manual point burying design method

Target

  • Easy to use;
  • Reduce code intrusion and do not affect business code reading

Brief description

  • The burial points are generally managed by pages;
  • The types of events for buried points are generally divided into: clicks, exposures, and page entry and departure;
  • The essence of burying points is to send requests and send business parameters at the right time.

Manage burial points by page

Created in each page directory to manage all buried events on the current page.

In order to reduce the impact of buried points on business code, the setting of each buried point is a method, in which data can be processed to obtain the data that the buried point needs to be sent.

The method of setting the buried point returns the object of the parameters that the buried point needs to be sent.

// src/views/PageA/

export default {
  // Manage by event type  CLICK: {
    back(ctx, data) {
      let { param1, param2 } = data;
      // ...process incoming data      return {
        eventValue: 'return',
        elementId: 'pageA-Return',
        // The processing parameters that need to be sent        customData: {
          param1,
          param2
        }
      };
    }
  }
}

Follow the principle of simple use and call the buried point

// src/views/PageA/

this.$track('', data);

Implement the above call

  • use()Aggregate the buried point settings in each page directory ()。
  • The aggregated buried point settings are managed as modules based on the page and the page folder name is used as module names.
  • Combined with routing management, you can obtain the name of the buried point configuration module of the current page.
  • Add a new one next$track()method.
// src/events/
import router from '@/router';

const ctx = ('@/views', true, /events\.js/);
const configs = {};
().reduce((configs, path) => {
  if (/\.\/(\w+?)\/events\.js/.test(path)) {
    const moduleName = RegExp.$1; // The first child    configs[moduleName] = resolveModule(moduleName, ctx(path));
  }
  return configs;
}, configs);

function resolveModule(moduleName, module) {
  return ().reduce((all, [EVENT_TYPE, events]) => {
    all[EVENT_TYPE] = (events).reduce((typeAll, key) => {
      typeAll[key] = buildTrackRequest(
        EVENT_TYPE.toLowerCase(),
        key,
        events[key]
      );
      return typeAll;
    }, {});
  });
}

function buildTrackRequest(eventType, trackName, trackSetting) {
  return function trackRequest(...args) {
    // Let's go back to see after reading    if (typeof trackSetting !== 'function') {
      trackSetting = obj2fn(trackSetting);
    }
    // Execute the user-defined method and return to the buried point to send parameters    const [success, result] = invokeUserFn((this, {}));
    if (!success) return result;
    // Pass in parameters and send a buried point request    return tracker(result);
  }
}

export function track(eventPath, ...args) {
  let event = configs;
  let seg;
  const segs = ('.');
  // 2-segment If the module name is not provided, you need to go to the routing configuration to retrieve it  if ( === 2) {
    const moduleName = ?.eventModule;
    if (!moduleName) {
      throwError(`${eventPath} Not set in routing configuration"" Or configured as3Segment`);
    }
    event = event[moduleName];
  }
  while ((seg = ())) event = event[seg];
  if (!event) throwError(`${eventPath} Does not exist`);
  //Bind the current calling environment to event  return (this, ...args);
}

function throwError(err) {
  throw Error(`[Track Error] ${err}`);
}

export default function install(Vue) {
  .$track = track;
}

Support object form for burying point settings

Many times, it may not be necessary to send business parameters, and it is easier to write as an object.

{
  CLICK: {
    back: {
      eventValue: 'return',
      elementId: 'pageA-Return',
    }
  }
}

Sometimes you only need to send simple business fields, without additional processing, and you also want to use the form of objects.

Supports {{param1}} template syntax, same as vue-template usage. (param1 is a property of the buried point calling component)

{
  CLICK: {
    back: {
      eventValue: 'return',
      elementId: 'pageA-Return',
      customData: {
        param1: '{{param1}}'
      }
    }
  }
}

Convert the object format buried point configuration into method form

const templateRE = /\{\{(.+?)\}\}/g;
// Handle object-formed point settingsfunction obj2fn(obj) {
  return function() {
    const that = this;
    // Process template strings    (function resolveObj(obj) {
      (obj).forEach(key => {
        const val = obj[key];
        // parse template string        if (typeof val === 'string' && (val)) {
          obj[key] = (templateRE, (...match) => {
            // The with syntax cannot be executed in js strict mode. The following is a change            return new Function(`with(this){return ${match[1]}}`).call(that);
          });
        }
        // Recursive processing        else if (isPlainObject(val)) resolve(val);
      });
    })(obj);
    return obj;
  };
}

Provide page-level parameter settings

Many times, the buried points under a page need to be sent with the same parameters, such as the page name.

Provides two hooks beforeModuleEach and afterModuleEach.

Generally, beforeModuleEach is used to set the common buried point parameters of the module (page), and then merge the separate buried point settings parameters to obtain all the parameters that need to be sent.

function resolveModule(moduleName, module) {
  // Get the hook set in the `` file  const { beforeModuleEach, afterModuleEach } = module;
  // Get dynamic settings hook  const { beforeHooks, afterHooks } = getHooksByModule(moduleName);
  beforeModuleEach && (beforeModuleEach);
  afterModuleEach && (afterModuleEach);
  
  return ().reduce((all, [EVENT_TYPE, events]) => {
    all[EVENT_TYPE] = (events).reduce((typeAll, key) => {
      typeAll[key] = buildTrackRequest(
        EVENT_TYPE.toLowerCase(),
        key,
        events[key],
        beforeHooks,
        afterHooks
      );
      return typeAll;
    }, {});
  });
}

Summarize

This is the end of this article about Vue manual point burying design. For more related content on Vue manual point burying design, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!