Vue引入外部JS包和Nuxt 引入外部JS包方法

起因

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

报错代码

// 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解决办法

参考资料

以上为 Vue 解决办法.


20240608 补充

Nuxt 引用外部代码

如果使用了 Nuxt.js,直接使用 head 就可以设置,不用上面还要装个扩展:

// pages/wechat/index.vue

<template>
    <div id="login_container">
</template>
<script  setup  lang="ts">
useHead({
script: [
{ src:  'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js' }, 
`new WxLogin({
    self_redirect: false,
    id: 'login_container',
    appid: 'wechat_app_id',
    scope: 'snsapi_login',
    redirect_uri: 'https://wechat_call_back.url',
    state: 'Main',
    style: '',
    href: '',
})`],
})
</script>

解释:
script 属性传递的数组数据,如果是对象,像 {src: “xxx.com”} 会生成:

<script src="xxxx.com"></script>

而如果是字符串则是包裹在JS标签里面:

<script>
//  字符串代码
</script>

道理是这个道理,可是JS 加载是有时间的,字符串里面的代码执行时,JS包还没有获取完成,然并 egg !

所以要在所有的依赖,加载完之后,再执行创建二维码代码,得用 onMounted:

<script setup lang="ts">
useHead({
  script: [{ src: 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js' }, ``],
})
// 使用了TS,定义下类型,不然会报错找不到类型.
declare let WxLogin:(any)
onMounted(() => {
  new WxLogin({
    self_redirect: false,
    id: 'login_container',
    appid: 'wechat_app_id',
    scope: 'snsapi_login',
    redirect_uri: 'https://wechat_call_back.url',
    state: 'Main',
    style: '',
    href: '',
  })
})
</script>
本作品采用《CC 协议》,转载必须注明作者和本文链接
天高地迥,觉宇宙之无穷;兴尽悲来,识盈虚之有数。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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