美文网首页
在vue中接入百度统计

在vue中接入百度统计

作者: _duck不必 | 来源:发表于2018-04-25 23:07 被阅读0次

    在申请百度统计后,会得到一段代码

    需要插入到每个页面的</head>标签前面

    在vue中只需要用vue-router的钩子函数即可解决:

    代码:


    //全局路由钩子

    router.beforeEach((to, from, next) => {

        setTimeout(()=>{

           var _hmt = _hmt || [];

           (function() {

            //每次执行前,先移除上次插入的代码

            document.getElementById('baidu_tj') && document.getElementById('baidu_tj').remove();   //判断有没有 baidu_tj  元素,有就删除

            var hm = document.createElement("script");

            hm.src = "https://hm.baidu.com/hm.js?xxxx";

            hm.id = "baidu_tj"

            var s = document.getElementsByTagName("script")[0];

            s.parentNode.insertBefore(hm, s);

           })();

        },0);

        next();

    })


    以上代码放到main.js中即可。

    相关文章

      网友评论

          本文标题:在vue中接入百度统计

          本文链接:https://www.haomeiwen.com/subject/fmyulftx.html