Summary of the knowledge of embedding instructions that Vue engineers must encapsulate

Summary of the knowledge of embedding instructions that Vue engineers must encapsulate

Preface

Recently, I need to implement a tracking function in my project. After sorting out the tracking documents of the product, I found that there are many scenarios for click tracking. Because we use Alibaba Cloud SLS log service to track points, we use manual intrusion code to track points. After deciding on the form of embedding, there are many technical implementation methods. Which one is better?

A little thought...

I decided to encapsulate a tracking instruction, which will be more convenient to use, because the instruction has a fine granularity and can hit the key points directly, which is quite suitable for the business scenarios mentioned above.

Instruction Basics

Before that, let's review the vue custom instructions. Here we only introduce the commonly used basic knowledge. For a more complete introduction, please refer to the official documentation.

Hook function

  • bind: Called only once, when the directive is first bound to an element.
  • inserted: called when the bound element is inserted into the parent node.
  • update: Called when the VNode of the component is updated.

Hook function parameters

  • el: The DOM element to which the directive is bound.
  • binding: An object containing the following properties:
    • value: The binding value of the directive. For example, in v-my-directive="1 + 1", the binding value is 2.
    • arg: Parameter passed to the command, optional. For example, in v-my-directive:foo, the parameter is "foo".
  • vnode: The current component vnode to which the instruction is bound.

Here is a little trick to share. There is no parameter in the hook function parameter that can directly obtain the current instance, but it can be obtained through vnode.context. This is also shared in my previous vue skills article. If you are interested, you can check it out.

text

Let's get to the point. The following will introduce the use of tracking instructions and how they are implemented internally.

Usage and ideas

Generally, when I encapsulate something, I will first determine how it should be used, and then start encapsulating it based on the usage. This will make the whole idea clearer, and you can also consider ease of use when defining usage, so as to avoid rework after encapsulation due to unsatisfactory usage.

The data reported by the tracking point is divided into public data (data that must be reported by each tracking point) and custom data (optional additional data, reported together with the public data). Then the public data will be processed uniformly internally, and the custom data needs to be imported from the outside. So there are two usages:

General Usage

<div v-track:clickBtn></div>

Custom Data

<div v-track:clickBtn="{other:'xxx'}"></div>

You can see that the tracking event is passed in the form of arg. Before this, I also saw that some friends encapsulated the tracking event in the form of value. But I personally prefer the arg format, which makes it easier to see at a glance what the corresponding buried event is.

In addition, the reported data structure is roughly as follows:

{   
    eventName: 'clickBtn'
    userId: 1,
    userName: 'xxx',
    data: {
        other: 'xxx'
    }
}

eventName is the event name corresponding to the embedding point. The public data is at the same level as it, and the custom data is placed in data.

accomplish

Define a track.js file

import SlsWebLogger from 'js-sls-logger'

function getSlsWebLoggerInstance (options = {}) {
  return new SlsWebLogger({
    host: '***',
    project: '***',
    logstore: `***`,
    time: 10,
    count: 10,
    ...options
  })
}

export default {
  install (Vue, {baseData = {}, slsOptions = {}) {
    const slsWebLogger = getSlsWebLoggerInstance(slsOptions)
    // Method to get public data let getBaseTrackData = typeof baseData === 'function' ? baseData : () => baseData
    let baseTrackData = null
    const Track = {
      name: 'track',
      inserted (el, binding) {
        el.addEventListener('click', () => {
          if (!binding.arg) {
            console.error('Track slsWebLogger event name is invalid')
            return
          }
          if (!baseTrackData) {
            baseTrackData = getBaseTrackData()
          }
          baseTrackData.eventName = binding.arg
          // Custom data let trackData = binding.value || {}
          const submitData = Object.assign({}, baseTrackData, {data: trackData})
          // Report slsWebLogger.send(submitData)
          if (process.env.NODE_ENV === 'development') {
            console.log('Track slsWebLogger', submitData)
          }
        })
      }
    }
    Vue.directive(Track.name, Track)
  }
}

The encapsulation is relatively simple and mainly does two things. First, it adds a click event to the DOM bound to the instruction, and second, it processes the reported data. When encapsulating tracking instructions, public data is passed in through baseData, which can increase versatility. The second parameter is some configuration parameters of the reporting platform.

Register the directive at initialization time:

import store from 'src/store'
import track from 'Lib/directive/track'

function getBaseTrackData () {
  let userInfo = store.state.User.user_info
  // Public data const baseTrackData = {
    userId: userInfo.user_id, // user id
    userName: userInfo.user_name // Username}
  return baseTrackData
}

Vue.use(track, {baseData: getBaseTrackData})

When Vue.use is called, it will automatically look for the install function to call, and finally register the directive globally.

Add some versatility

In addition to click tracking, if there are scenarios such as stay tracking, the above instructions are not applicable. To this end, a manual call form can be added.

export default {
  install (Vue, {baseData = {}, slsOptions = {}) {
    // ...
    Vue.directive(Track.name, Track)
    // Manually call Vue.prototype.slsWebLogger = {
      send (trackData) {
        if (!trackData.eventName) {
          console.error('Track slsWebLogger event name is invalid')
          return
        }
        const submitData = Object.assign({}, getBaseTrackData(), trackData)
        slsWebLogger.send(submitData)
        if (process.env.NODE_ENV === 'development') {
          console.log('Track slsWebLogger', submitData)
        }
      }
  }
}

This way of mounting to the prototype can be conveniently called through this on each component instance.

export default {
    // ...
    created () {
        this.slsWebLogger.send({
            //...
        })
    }
}

Summarize

This article shares the process of encapsulating tracking instructions. Encapsulation is not difficult to achieve. There are mainly two forms. Click tracking listens for click reports by binding DOM click events, while manual calls are provided in other scenarios. Mainly want to record the idea of ​​encapsulation and how to use it. The tracking point implementation has also been adjusted according to the business. For example, the registration tracking point instruction can accept the configuration parameters of the reporting platform. After all, people are alive and code is dead. As long as it meets business needs and can be maintained, you can use it in any way that is comfortable for you.

This concludes this article about the knowledge summary of the tracking instructions that Vue engineers must encapsulate. For more relevant Vue encapsulation tracking instructions, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Implementation of front-end embedding in Vue project
  • An example of Vue manual embedding design method

<<:  Detailed explanation of common usage of pseudo-classes before and after in CSS3

>>:  5 tips for writing CSS to make your style more standardized

Recommend

How to recover files accidentally deleted by rm in Linux environment

Table of contents Preface Is there any hope after...

Sample code for implementing DIV suspension with pure CSS (fixed position)

The DIV floating effect (fixed position) is imple...

Detailed instructions for installing Jenkins on Ubuntu 16.04

1. Prerequisites JDK has been installed echo $PAT...

A brief discussion on the principle of js QR code scanning login

Table of contents The essence of QR code login Un...

What are the advantages of MySQL MGR?

MGR (MySQL Group Replication) is a new feature ad...

How to process blob data in MySQL

The specific code is as follows: package epoint.m...

Detailed explanation of JavaScript's Set data structure

Table of contents 1. What is Set 2. Set Construct...

Docker swarm simple tutorial

swarm three virtual machines 132,133,134 1. Initi...

Solution to the ineffectiveness of flex layout width in css3

Two-column layout is often used in projects. Ther...

Configure VIM as a C++ development editor in Ubuntu

1. Copy the configuration file to the user enviro...

MySQL 5.7.17 installation and configuration tutorial for Mac

1. Download MySQL Click on the official website d...

Explanation of Dockerfile instructions and basic structure

Using Dockerfile allows users to create custom im...

Win32 MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...