Vue引入外部JS包报错Tags with side effect ...解决办法

起因

网站应用接入微信登录,通过在网站上展示登录二维码,而不用跳转到微信网页登录.
微信网站应用文档

报错代码

// login.vue
<template>
  <UContainer class="bg-primary">
    <div id="login_container"></div>
  </UContainer>
  <script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
</template>

报错详情:

Vue3模版引用外部js报错Tags with side effect (<script> and <style>) are ignored in client component解决办法

造成问题原因

在Vue3中,直接添加外部 script 被认为是不安全有风险的,会被强制终止掉.

解决版本

引入 VueUse 包 vueuse/core

npm i @vueuse/core

修改代码

// login.vue
<template>
  <UContainer class="bg-primary">
    <div id="login_container"></div>
  </UContainer>
</template>

<script setup lang="ts">
declare class WxLogin {
  constructor(config: any);
} 
import { useScriptTag } from "@vueuse/core";
useScriptTag(
  "https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js",
  (el: HTMLScriptElement) => {
    var obj = new WxLogin({
      self_redirect: true,
      id: "login_container",
      appid: "your wechat appid",
      scope: "snsapi_login",
      redirect_uri: "https://your.site/user/wechat-verify",
      state: "bigbug_demo",
      style: "",
      href: "",
    });
  }
);
</script>

效果:
Vue3模版引用外部js报错Tags with side effect (<script> and <style>) are ignored in client component解决办法

参考资料

本作品采用《CC 协议》,转载必须注明作者和本文链接
莫等闲,白了少年头,空悲切
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
39
粉丝
13
喜欢
75
收藏
67
排名:294
访问:3.2 万
私信
所有博文
社区赞助商