You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js项目中如何修改SweetAlert2(Swal2)弹出框的自定义字体族

失效核心原因

  • 你写的<style scoped>样式只会作用于当前组件内部的DOM节点,Swal2的弹出层是直接挂载在全局body节点下的,不属于当前组件的DOM树,因此scoped样式无法命中元素
  • 选择器书写错误,Swal2的内置类名格式为.swal2-*,你写的swal2title既没有加类选择器的.,拼写也不符合Swal2的命名规则
  • 直接修改body字体不生效是因为Swal2内置样式已经给弹出层各元素单独设置了font-family,继承的优先级低于元素直接绑定的样式,因此无法覆盖

解决方法

方法1:全局样式覆盖(最简单,适配所有Swal弹出框)

直接在全局样式文件或者App.vue的非scoped样式块中添加以下样式,正确命中Swal2的对应元素:

/* 不需要加scoped */
/* 标题字体 */
.swal2-title {
  font-family: '你的字体名', sans-serif !important;
}
/* 内容文本字体 */
.swal2-html-container {
  font-family: '你的字体名', sans-serif !important;
}
/* 按钮字体 */
.swal2-confirm, .swal2-cancel {
  font-family: '你的字体名', sans-serif !important;
}

方法2:自定义类名局部修改(仅作用于指定弹出框,不污染全局)

调用Swal.fire时通过customClass参数给当前弹出框添加自定义类,再对应写样式:

function fireNo(){
    Swal.fire({
          icon: 'warning',
          title: 'titletext',
          showCloseButton: true,
          text: 'texttext',
          focusConfirm: false,
          confirmButtonText: 'buttontext',
          // 新增自定义类配置
          customClass: {
            title: 'my-swal-title',
            htmlContainer: 'my-swal-content',
            confirmButton: 'my-swal-confirm'
          }
      })
}

对应全局样式:

.my-swal-title {
  font-family: 'fontname', sans-serif !important;
}
.my-swal-content {
  font-family: 'fontname', sans-serif !important;
}
.my-swal-confirm {
  font-family: 'fontname', sans-serif !important;
}

方法3:使用深度选择器在当前组件scoped样式中修改

如果不想写全局样式,也可以用Vue的深度选择器穿透scoped限制:

/* Vue2写法 */
<style scoped>
/deep/ .swal2-title {
  font-family: 'fontname' !important;
}
/deep/ .swal2-html-container {
  font-family: 'fontname' !important;
}
</style>

/* Vue3写法 */
<style scoped>
:deep(.swal2-title) {
  font-family: 'fontname' !important;
}
:deep(.swal2-html-container) {
  font-family: 'fontname' !important;
}
</style>

内容的提问来源于stack exchange,提问作者Cassis Frappe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:39:01