Vue template中包含script标签的写法

Chason
2021-03-13 / 0 评论 / 0 点赞 / 1,027 阅读 / 1,068 字
温馨提示:
本文最后更新于 2021-03-13,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

最近项目中有一段谷歌广告代码 必须放在template中,但是vue会提示报错:

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

所以尝试使用 createElement 的写法,果然解决了问题。。。代码如下

<script>
  export default {
    name: 'gb-ad',
    props: {
      unit: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        // active is for fixing the bug that AD not showing when back to keep-alive page
        active: true
      }
    },
    render(createElement) {
      const self = this
      if (!this.active) {
        return
      }

      return createElement('div',
        {
          attrs: {
            id: self.unit
          }
        },
        [
          createElement('script', 'googletag.cmd.push(function() { googletag.display("' + self.unit + '"); });')
        ])
    },
    activated() {
      this.active = true
    },
    deactivated() {
      this.active = false
    }
  }
</script>

原文:https://cloud.tencent.com/developer/article/1499093

0

评论区