vue-nuxt-ssr 做谷歌,百度统计以及google,facebook埋点总结

前言


众所周知,做电商都知道seo的重要吗,最近在用vue+nuxt.js做跨境电商时就有一个需求是要做谷歌的统计和埋点以及facebook的统计和埋点。因为对这个框架不是很熟悉,所以好多文档也不是很清楚,这样就导致做的过程中很费劲。以下就记录一下是如何做埋点和统计的。

第一步:
  • 1,首先,在官方文当中有介绍到如何集成google统计分析服务,这里就不详细介绍了,这里主要介绍一下如何使用google做网站的埋点。

  • 2,做谷歌埋点我是参考的谷歌的埋点的官方文档,再加上其他的一些文档,这里把官方文档的链接贴出来。
    Google Analytics.js 谷歌分析,统计,埋点网址

  • 3, 如果是在没有做ssr - seo - nuxt的项目中直接在index.html中引入analytics.js就好了。如下图官网中所说的一样。
    在这里插入图片描述

  • 4,但是在nuxt.js就不能这么做了,就要用官网中介绍的方法,在第二步中详细介绍

第二步:
  • 1,首先要在plugins文件夹下新建一个ga.js(这里的ga.js是自己命名的哦)文件,这个js 主要是以nuxt的方式引入Analytics.js
  • 2,这样引进来只适合用户统计分析,这里边的全局函数ga在项目中是找不到的,只能在当前文件使用。
//这句是只有生产环境才会统计,为了方便测试一开始从测试环境也要使用
// if (process.client && process.env.NODE_ENV === 'production') {
if (process.client) {
  /*
   ** Google 统计分析脚本
   */
  (function (i, s, o, g, r, a, m) {
    i.GoogleAnalyticsObject = r;
    (i[r] =
      i[r] ||
      function () {
        ;
        (i[r].q = i[r].q || []).push(arguments)
      }),
    (i[r].l = 1 * new Date());
    (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0])
    a.async = 1
    a.src = g
    m.parentNode.insertBefore(a, m)
  })(
    window,
    document,
    'script',
    'https://www.google-analytics.com/analytics.js',
    'ga'
  )
  /*
   ** 当前页的访问统计
   */
  ga('create', 'UR-1323268912-1', 'auto')     //这里要填写你自己的google代码  code
}

export default ({
  app: {
    router
  },
  store,
}) => {
  /*
   ** 每次路由变更时进行pv统计
   */
  //   if (process.client && process.env.NODE_ENV === 'production') {
  if (process.client) {
    router.afterEach((to, from) => {
      /*
       ** 告诉 GA 增加一个 PV
       */
      ga('set', 'page', to.fullPath)
      ga('send', 'pageview')
      ga('require', 'ec');
    })
  }

}

  • 3,要是在项目中再加入google埋点的功能就需要使用到nuxt.js的另一个方法inject方法了。
    这里没用过inject方法的应该是一脸懵逼,先把官方文档nuxt-inject方法贴出来,
    官方说的很详细了,直接用这个方法在之前新建的ga.js中注入全局的函数,然后在项目中使用,方法如下
上边的引入Analytics.js跟上边一样,只不过在这里在注入一个全局的函数,看下边的inject就是了。
export default ({
  app: {
    router
  },
  store,
}, inject) => {
  /*
   ** 每次路由变更时进行pv统计
   */
  //   if (process.client && process.env.NODE_ENV === 'production') {
  if (process.client) {
    inject('hello', msg => console.log(`Hello ${msg}!`))
   // googlePoint 注入的函数名字,argume 传入的参数
    inject('googlePoint', argume => {
      console.log(argume);
      //在当前这个js内是可以拿到ga这个google默认分发出来的全局函数的
      ga('ec:addProduct', {
        'id': argume.productId, // Product ID (string).
        'name': argume.productName, // Product name (string).
        'price': argume.price,
      });
      ga('set', 'currencyCode', argume.currencyCode);
      ga("ec:setAction", "add");
    })
    router.afterEach((to, from) => {
      /*
       ** 告诉 GA 增加一个 PV
       */
      ga('set', 'page', to.fullPath)
      ga('send', 'pageview')
      ga('require', 'ec');
    })
  }

}
  • 4,接下来就是在项目中使用了,这里就举一个添加购物车埋点的例子
<template>
  <el-button
        type="danger"
        plain
        @click="addCar()"
        v-loading="isLoadingAddCar"
        >Add to cart</el-button
      >
<script>
    export default {
         data(){
             return{
                 isLoadingAddCar:false,
              }
           },
        methods:{
                 addCar() {
      this.isLoadingAddCar = true
      let google_price = "";
      //这里是判断是否为折扣价的,就是为了传给谷歌埋点的参数
       if (this.skuSalesVal) {
             google_price = (this.skuSalesVal.price / 100).toFixed(2);
          }else{
             google_price = (this.productBasicVo.minPrice / 100).toFixed(2);
          }
      let national_google_currency = JSON.parse(localStorage.getItem('national_currency'));
      let google_facebook_params = {
        productId:this.form.productId,
        productName:this.productBasicVo.name,
        price:google_price,
        currencyCode:national_google_currency.name, 
      }
      this.$hello('这里是测试inject');      //这里也是对应ga.js里边的inject注入的hello方法
     //这就是在调用在ga.js中全局注入的googlePoint,方法
      this.$googlePoint(google_facebook_params);
       //这就是在调用在facebook.js中全局注入的googlePoint,方法
      this.$faceBook_point(google_facebook_params);
      this.$axios
        .post('/web/api/product/add-cart', this.form)
        .then((res) => {
          this.isLoadingAddCar = false
          this.$refs['add-success'].dialogVisible = true
          this.$refs['add-success'].carNum = res.data
          this.form.quantity = 1
          this.$store.dispatch('shopCar/getCarList')
        })
        .catch(() => {
          this.isLoadingAddCar = false
        })
    },
         }
    }
</script>
</template>

这里是一次更新,最近发现谷歌的埋点不管用了,经过排查才发现是谷歌的收录和接受埋点的js更改了。

接下来会介绍更新后的埋点怎么做。

  • 1,首先安装vue-gtag
    执行命令npm install vue-gtag --save
  • 2,在plugins文件夹下创建gtag.js,内容如下:
import Vue from 'vue'
import VueGtag from 'vue-gtag'

Vue.use(VueGtag, {
  config: {
    id: 'G-WCNCFN42QT'
  }
})

export default ({
  app: {
    router
  },
  store,
}, inject) => {
  if (process.client) {
    //当用户进行登录
    inject('googleLogin', params => {
      gtag('event', 'login', params);
    });

    //当用户进行注册
    inject('googleRegister', params => {
      gtag('event', 'register', params);
    });
    //当用户查看商品时触发
    inject('googleViewPromotion', params => {
      gtag('event', 'view_promotion', params);
    });
    //当用户开始结帐时触发
    inject('googleBeginCheckout', params => {
      gtag('event', 'begin_checkout', params);
    });
  }
}

  • 3,其他的跟老的ga.js收录方法一致,也是用inject方法分发出来,在项目中使用。
第三步:那么同理,facebook的统计脚本和埋点也是这么引入

在plugins下边新建facebook.js

    if (process.client) {
        /*
         ** facebook 埋点
         */
        !function (f, b, e, v, n, t, s) {
            if (f.fbq) return; n = f.fbq = function () {
              n.callMethod ?
                n.callMethod.apply(n, arguments) : n.queue.push(arguments)
            };
            if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0';
            n.queue = []; t = b.createElement(e); t.async = !0;
            t.src = v; s = b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t, s)
          }(window, document, 'script',
            'https://connect.facebook.net/en_US/fbevents.js');
          fbq('init', '44688333333333');   //这里要填写你自己的facebook代码
      }
      
      export default ({
        app: {
          router
        },
        store,
      }, inject) => {
        /*
         ** 每次路由变更时进行pv统计
         */
        if (process.client) {
          inject('faceBook_point', argume => {
            console.log(argume);
            fbq('track', 'AddToCart', {
                content_type: 'product',
                content_ids: argume.productId,
                content_name: argume.productName,
                currency: argume.currencyCode,
                value: argume.price,
              });  
         
          })
          router.afterEach((to, from) => {
            /*
             ** 告诉 GA 增加一个 PV
             */
          fbq('track', 'PageView');
          })
        }
      
      }
      
第四步:百度统计也是如此引

在plugins下新建baidu.js文件

    if (process.client) {
        /*
         ** 百度统计
         */
             var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?888888888888888";  //这里填写你自己的百度代码
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
      }
      
      export default ({
        app: {
          router
        },
        store,
      }) => {
        /*
         ** 每次路由变更时进行pv统计
         */
        if (process.client) {
          router.afterEach((to, from) => {
                      var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?455234523523523543";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
          })
        }
      
      }
      
第五步:最后在nuxt.config.js中的plugins下引入这几个统计的js文件
export default {
plugins: [
    {
      src: '@/plugins/ga.js',
      mode: 'client'               //只在客户端生效
    },
    {
      src: '@/plugins/facebook.js',
      mode: 'client'
    },
    '@/plugins/jumpBaseUrl',
  ],


   }

这样就实现了谷歌,facebook,百度统计的功能

结束语

在写这个功能的时候由于对新框架不是很了解,所以折腾的时间比较久,而且也踩了很多坑,在加上文档没有看全面,有的方法自己不知道,所以记录下来,以后慢慢学习使用。

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值