首页 > 解决方案 > 从 Vue 中添加 Google 跟踪代码管理器(在获得同意后)

问题描述

在用户同意后,我正在尝试加载 Google 跟踪代码管理器。我知道那里有很多选择,无需使用 Vue 就可以做到,但它们要么是厚实的、庞大的和/或昂贵的。他们中的大多数也很丑陋。

为了实现 Google 跟踪代码管理器,必须在<head>'first-thing-in-the-body' 中添加代码片段。这两者都不是在著名的#app-vue-instance 中。

我在 WordPress 中使用 Vue,所以我没有/不会有 Vue-Router 或 Vuex。它是一个 Nginx/Apache 服务器,路由由 WordPress 控制。

这是我的代码:

import Vue from 'vue';
Vue.mixin( cookieMixins ); // loads getCookie and setCookie

const app = new Vue({
  el: '#app',
  mixins: [
    cookieMixins
  ],
  data: {
    cookiesAccepted: false
  },
  mounted() {
    this.cookiesAccepted = ( this.getCookie( 'cookie_consent' ) === 'true' ); 
    this.addGtm();
  },
  methods: {
    acceptCookies() {
      this.setCookie( 'cookie_consent', 'true', 30 );
      this.cookiesAccepted = true;

      this.addGtm();
    },
    addGtm(){
      if( this.cookiesAccepted ){

        //
        // I want to add the 
        // Google Tag Manager tags (both the 
        // snippet for the head and the body here.
        //

      }
    }
  },
});

这是一种符合 GDPR 的尝试, - 在用户同意之前不加载任何跟踪代码。

我是否需要将其作为 JavaScript 函数放在 Vue 实例之外?如果是这样, - 那会怎样?我可以从我的 Vue 实例中调用它吗?


我试过的


额外信息

对于使用它的其他人:您可以在此处查看 getCookie 和 setCookie JavaScript 函数

标签: javascriptvue.js

解决方案


推荐阅读