解决Vue template中无法使用script标签的问题

文章目录

问题背景

在公司写了个网页,网站运营搞起来了流量还不错,于是老板叫我们在网站中各个位置中插入广告位,谷歌提供的广告位大概长这样:

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=xxx"
     crossorigin="anonymous"></script>
<!-- HomeTop_square -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="xxx"
     data-ad-slot="xxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

那一刻我觉得直接把这段代码粘到Vue 组件 template中不就ok了,于是创建了一个Vue组件 Advertising:

<template>
  <div>
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=xxx"
            crossorigin="anonymous"></script>
    <!-- HomeTop_square -->
    <ins class="adsbygoogle"
         style="display:block"
         data-ad-client="xxx"
         data-ad-slot="xxx"
         data-ad-format="auto"
         data-full-width-responsive="true"></ins>
    <script>
      (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
  </div>
</template>

没想到嘴角刚翘起来没多久控制台就报了个错:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

大概就是说,不允许在template中使用script标签,script的内容将不会被解析; 于是我换了种思路,尝试通过v-html 指令去注入整段html内容。。。

结果自然是也不行, script的逻辑不会被执行

再次尝试使用innerHtml去注入

结果自然是也不行, script的逻辑不会被执行

再次尝试使用appendChild去注入dom

结果自然是也不行, script的逻辑不会被执行

后来百度了好久发现一个开源组件 vue-append ,已经封装好了一个客插入带有script标签的html段,详细使用方法官网已经有了,我就不必赘述,我就简单演示一下我的使用方法吧。

  • npm引入
npm install vue-append --save
  • 在vue-cli构建的项目的main.js配置文件进行配置
import VueAppend from 'vue-append'
Vue.use(VueAppend)
  • 创建广告位组件, 使用v-append直接注入带有script 的 html段
<template>
  <div v-append="adhtml"></div>
</template>

<script>
export default {
  name: "Advertising",
  props: {
    adhtml: String
  }
}
</script>

<style scoped>

</style>
  • 在调用Advertising组件的父组件中给Advertising组件赋值文字开头的那段代码的即可测试。

总结:

开源就是爽…

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值