preface

I met the requirement of a page and interface traffic statistics before, then I found many posts on the Internet, and found that some of them were not written in detail, so I sorted them out today and modified them today. There was a slight problem before, that is, this.$matomo could not be obtained. So there are two ways.

The body of the

Vue – matomo way

  • The first stepThe first, of course, is Matomo
npm i vue-matomo
Copy the code
  • Step 2 Register Matomo in main.js
import VueMatomo from 'vue-matomo'
Vue.use(VueMatomo, {
  host: 'http://matomo.na.xyz'// set your own piwik server address and siteId. // set your own piwik server address and siteId.$matomo
  trackerFileName: 'matomo', // Automatically register the router by router: router, // // Whether to request permission before sending tracing information // // defaultfalse
  requireConsent: false.enableLinkTracking: true, // // whether to trace the initial page // // defaulttrue
  trackInitialView: false, // // final trace JS file name // // default'piwik'
  trackerFileName: 'matomo',
  debug: false
});
Copy the code

It is also possible to present a public file to dynamically maintain your Piwik server address and website

import VueMatomo from 'vue-matomo'// dynamically maintained file import baseUrlto from'./utils/baseUrlto'// This code is used to get the current loaded path and maintain the file array to match the corresponding collection object.let uitem
baseUrlto.map(e => {
  if(document.URL.indexOf(e.environmentUrl) ! == -1) { uitem = e } })if(! Uitem) {uitem = baseUrlto[0]} vue. use(VueMatomo, {host: uitem.staurl, // Uitem. staId, // Here is the matched siteId value // Automatically register the router according to the router: router, // // Whether to request permission before sending trace information // // defaultfalse
  requireConsent: false.enableLinkTracking: true, // // whether to trace the initial page // // defaulttrue
  trackInitialView: false, // // final trace JS file name // // default'piwik'
  trackerFileName: 'matomo',
  debug: false
});
Copy the code

Attach the code for baseUrlto

Const statistics = [// first item of array, that is, the default url of test statistics is {staUrl:'//analytics.baowei-inc.com/'// staId:'2', // statistics ID environmentUrl:'default'
  },
  {
    staUrl: '//analytics.baowei-inc.com/'// Development environment statistics website staId:'2', // statistics ID environmentUrl:'http://bwcaigou.baowei-inc.com'
  },
  {
    staUrl: '//analytics.baowei-inc.com/'// Production environment statistics website staId:'1', // statistics ID environmentUrl:'http://portal.baowei-inc.com'
  },
  {
    staUrl: '/ / 106.12.95.245:8888 /', // Local environment statistics website staId:'2', // statistics ID environmentUrl:'http://localhost:'}]export default statistics

Copy the code
  • The third step is to listen for route changes in app.vue
watch: {
      '$route' () {
        letlocationHash = window.location.hash; Sessionstorage.setitem (* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"hashLocation",locationHash); }},Copy the code
  • Fourth step, and then in each jump will need to be counted in the component, add a tracking information code, each page component, for repeated use of sub-components do not need to add, pop-ups and other do not need to, for page level components,// pure JS does not need this step
 created(){
      const hashLocation= sessionStorage.getItem("hashLocation"); // Get the route name of the current page in the cache const newLocation =hashLocation.split("# /") [1]; // Note that full path matching is used in thehashMode, because the address is carried#, so the url in the page report needs to be rewritten to remove #
       window._paq.push(['setCustomUrl'."http:baidu.com"+"/"+newLocation); // Overwrite the page report URL, you can customize the page URL, plus the page route window._paq.push(['trackPageView'].hashLocation); // page name, can be customized page name}Copy the code

Specifically, the setCustomUrl function is to reset the URL, because in the page URL statistics of Matomo, it is through the URL statistics, if not processed, will automatically count the next level of the domain name directory as the same page, that is to say, /#/ will be read as a page url, if not, then every page visited will be counted as /index page.

Directories after one level are counted as subdirectories

// Note that full path matching is used in thehashMode, because the address is carried#, so the url in the page report needs to be rewritten to remove #
      window._paq.push(['setCustomUrl'."http:baidu.com"+"/"+newLocation); // Non-full path window._paq.push(['setCustomUrl'."http://www.baidu.com"+"/"+newLocation); // Full path // cover the page report URL, you can customize the page URL, plus the page routeCopy the code

The important thing to say twice is that you need the full path string, otherwise you still get #.

  • Step 5, in fact, at this point, the normal statistics have been able to, the following are some optimization steps.

    Statistics on interfaces

    Statistics for interfaces are code to send statistics in the request interceptor

    import pathToname from '@/utils/pathname'/ / request interceptor service. Interceptors. Request. Use (config = > {if (config.url.indexOf('/login') === -1) {// Set user name const name = store.getterslet urlName
       let curl = config.url
       curl = curl.split('? ') [0] | | curl / / will be asked to address into Chinesefor (const k in pathToname) {
         if (curl === k) {
           urlName = pathToname[k]
         } else {
           const kurl = k
           const turl = curl
           const karr = kurl.split('/')
           if (karr[karr.length - 1] === The '*') {// represents the last bit of * karr.splice(karr.length-1, 1) const karr1 = turl.split('/')
             karr1.splice(karr1.length - 1, 1)
             const str = karr.join('/')
             const str2 = karr1.join('/')
             if (str === str2) {
               urlName = pathToname[k]
             }
           } else {
             karr.splice(karr.length - 2, 1)
             const str = karr.join('/')
             const karr1 = turl.split('/')
             karr1.splice(karr1.length - 2, 1)
             const str2 = karr1.join('/')
             if (str === str2) {
               urlName = pathToname[k]
             }
           }
         }
       }
       // urlName = urlName || 'other'
       urlName = urlName || config.url
       window._paq.push(['setCustomUrl', `${document.URL.split('/#')[0]}${curl}123`])
       window._paq.push(['setDocumentTitle', urlName])
       window._paq.push(['setUserId', name])
       window._paq.push(['trackPageView'])}Copy the code

Of course, I use here is the JS way principle is the same, the above code, IS I do the statistics of the address name of the Chinese culture matching. Because of the diversity of interfaces, a process needs to be done. For example, in the path parameter transmission, only the parameter is changed, but the address is not changed, so it cannot be considered as a new address, so it needs to be matched. Code did not write too complex, step by step in-depth, basically very easy to understand.

Attach the code for pathName. Used to match the address to Chinese statistics,:

Const changeName = {// goods related API'/pdc/api/v1/dic/query': 'Basic Records Management - Access to Goods Information'.'/pdc/api/v1/product/query': 'Basic Records Management - Access to Goods Details', // role related API'/api/root/list': 'Basics - Get Menu permissions'.'/api/createRole': 'Rights Management - Create Roles'.'/api/checkRoleName': 'Rights Management - Check whether a role exists'.'/api/custom/master/permission': 'Rights Management - Get a list of external customer roles'.'/api/internal/user/info': 'Basics - Get user information'// Statement related API'/statement/financialForm': 'Financial Management - Get JIT Financial List'.'/statement/export': 'Financial Management - Exporting JIT Financial Statements'.'/statement/count': 'Financial Management - Get JIT data summary entry', // trade related API(to be determined) // user related API'/api/internal/user/list': 'Permission Management - Get a list of external users'.'/api/internal/custom/list': 'Permission Management - Get external Customer List'.'/user/create': 'Permission Management - Create user'.'/user/update': 'Rights Management - Modify User Information'.'/api/user/password': 'Rights Management - Changing user passwords'// Order list related API'/order/api/v1/orderConfirmation': 'B2B Transaction Management - Order Submission '.'/order/api/v1/serviceApprove': 'B2B Transaction Management - Confirm Order '.'/order/api/v1/serviceRefuse': 'B2B Transaction Management - Reject orders'.'/order/api/v1/getDispatchSelectInfo': 'B2B Transaction Management - Get Order Dictionary data '.'/order/api/v1/import/productList': 'B2B Transaction Management - Import Order Data '.'/order/api/v1/*/orderInformation': 'B2B Transaction Management - Get basic Order Information '.'/order/api/v1/*/customerCode': 'B2B Transaction Management - Check if customer code exists'.'/order/api/v1/*/discount': 'B2B Transaction Management - Import Order Discounts'.'/order/api/v1/*/occupyInventory': 'B2B Transaction Management - Export capture Results'.'/order/api/v1/createDispatch': 'B2B Transaction Management - Submission of Invoices'.'/order/api/vi/dispatchCancel': 'B2B Transaction Management - Cancel Invoices'.'/order/api/vi/*/orderCancel': 'B2B Transaction Management - Cancel Orders'.'/order/api/v1/dispatchApprove': 'B2B Transaction Management - Approved Invoices'.'/order/api/v1/dispatchRefuse': 'B2B Transaction Management - Rejection of Invoices'.'/order//api/v1/confirmSubmissionApproval': 'B2B Transaction Management - Order Submission Approval '.'/order/api/v1/orderStatus': 'B2B Transaction Management - Get Order Status'.'/bff/api/v1/dispatch/*': 'ODS Management - Get Invoice basic information '.'/bff/api/v1/receive/*': 'ODS Management - Access to Basic information on receipts'.'/bff/api/v1/vend-cust': 'ODS Management - Get customer List information '.'/bff/api/v1/warehouses': 'ODS Management - Real-time access to Warehouse information '.'/bff/api/v1/dict/type': 'ODS Management - Warehouse Type Query '.'/bff/api/v1/dispatch/_export': 'ODS Management - Guide shipping manifest Information '.'/bff/api/v1/receive/_export': 'ODS Management - Export receipt information '.'/bff/api/v1/dict/type/_list': 'ODS Management - Query dictionary data '.'/bff/api/v1/dispatch/_page': 'ODS Management - Query single List of Shipments'.'/order/api/v1/orderList': 'B2B Transaction Management - Query Order List '.'/order/api/v1/orderDetail': 'B2B Transaction Management - Get order List '.'/order/api/v1/orderDispatchInfo': 'B2B Transaction Management - Obtain Order invoice Information '.'/order/api/v1/dispatchList': 'B2B Transaction Management - Obtain order Delivery List '.'/order/api/v1/confirm': 'B2B Transaction Management - Modify repository results'.'/order/api/v1/toBeConfirmedDispatch': 'B2B Transaction Management - View historical Invoice Information '.'/order/api/v1/cumulativeState': 'B2B Transaction Management - Capture results information '
}
export default changeName
Copy the code

Pure JSmatomo statistics, the effect is the same as above, relatively simple, just a step, in main.js registration, and then can be used in other pages.

// dynamically maintained file import baseUrlto from'./utils/baseUrlto'
let uitem
  baseUrlto.map(e => {
    if(document.URL.indexOf(e.environmentUrl) ! == -1) { uitem = e } })if(! uitem) { uitem = baseUrlto[0] } var _paq = _paq || [] window._paq = _paq /* tracker methods like"setCustomDimension" should be called before "trackPageView" */
  const arr = (document.URL.split(The '#')[1]).split('/')
  let CurlName
  if (arr.length >= 5) {
    arr.splice(arr.length - 1, 1)
    const str = arr.join('/')
    CurlName = urlName[str]
  } else {
    const str = arr.join('/')
    CurlName = urlName[str]
  }
  CurlName = CurlName || 'Other Pages'
  sessionStorage.setItem('urlName', CurlName) // Page refresh is performed once, recording the page access _paq.push(['setCustomUrl', `${document.URL.split('/#')[0]}${document.URL.split('/#')[1]}`])
  _paq.push(['setDocumentTitle', CurlName])
  _paq.push(['trackPageView'])
  _paq.push(['enableLinkTracking']);
  (function() {
    const u = uitem.staUrl
    _paq.push(['setTrackerUrl', u + 'matomo.php'])
    _paq.push(['setSiteId', uitem.staId])
    var d = document
    var g = d.createElement('script')
    var s = d.getElementsByTagName('script')[0]
    g.type = 'text/javascript'
    g.async = true
    g.defer = true
    g.src = u + 'matomo.js'Supachai panitchpakdi arentNode. InsertBefore (g, s)}) () / / window. The other pages _paq. Push (['setDocumentTitle'.'ODS Management - Shipping List Page '])
      window._paq.push(['trackPageView'])
Copy the code

Js way is relatively simple, on a step, other conversion address, Chinese and so on and the above way is the same, if you have any problem with the first way, and did not reply in time, you can directly use JS way.

Other words will not be repeated, Chinese transformation, each person has their own understanding, can achieve the effect on the line.

Js statistics are similar. If you need anything, leave a comment and I’ll post it later.

conclusion

Vue-matomo and JS traffic statistics have been normally used in the actual project even if the sorting is completed, so there should be no problems normally. Come on, guys