vue百度统计代码

1. 在webpack.base.config.js中写双环境plugin

或者在webpack.dev.config.js和webpack.prod.config.js分别写plugin插件引入

插件如下:

'use strict';
var track =  {
  hasTrack: true,
  hash: 'xxxx'
};


function HTMLWebpackMonitorPlugin(options) {
  this.options = options;
}

HTMLWebpackMonitorPlugin.prototype.apply = function(compiler) {
  compiler.plugin('compilation', function(compilation, options) {
    compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) {

      if (track.hasTrack) {
        var script = `
                        <script>
                            var _hmt = _hmt || [];
                            (function() {
                              var hm = document.createElement("script");
                              hm.src = "https://hm.baidu.com/hm.js?` + track.hash + `";
                              var s = document.getElementsByTagName("script")[0]; 
                              s.parentNode.insertBefore(hm, s);
                            })();
                        </script>
                    `;
        htmlPluginData.html = htmlPluginData.html.replace('</body>', script + '</body>');
      }



      callback(null, htmlPluginData);
    });
  });
};

module.exports = HTMLWebpackMonitorPlugin;

引入方法:

const htmlWebpackMonitorPlugin = require('./plugins/html-webpack-monitor-plugin')
new htmlWebpackMonitorPlugin()

router.js中在路由守卫的时候使用

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  // 检查路由元信息,是否必须登录
  if (to.matched.some(record => record.meta.loginRequired)) {
    // console.log('配置文件常量:CFG=', CFG)
    // 获取当前用户登录状态
    // TODO: 当前用户登录状态  环境变量
    console.info(store)
    let loggedIn = store.state.app.user
    // console.log('logedIn:', loggedIn)
    if (!loggedIn) {
      window.location.href = CFG.API_PASSPORT_URL.substring(0, CFG.API_PASSPORT_URL.length - 1) + '?from=' + CFG.ROOT_URL.substring(0, CFG.ROOT_URL.length - 1) + '#' + to.fullPath
      if (window._hmt) {
        console.log('进入了window._hmt')
        window._hmt.push(['_trackPageview', '/#' + to.fullPath])
      }
      next(false)
    } else {
      next()
    }
  } else {
    next()
  }
})

猜你喜欢

转载自blog.csdn.net/gwdgwd123/article/details/82594130