uniapp web 灵活控制 style scoped

前言

郑重承诺以下内容不由 AI 生成

最近在一个 uni-app vue3 的项目,运行到 web 的时候发现,页面中不添加 scoped 样式,仍然是开启了 scoped 的效果,导致样式无法全局生效,经过一番查找,发现是 uni-app 默认所有页面都开启了 scoped,本文记录如何解除这个限制。

测试代码

html 复制代码
<template>
  <view class="page">
    <view class="hero">
      <text class="eyebrow">Main package</text>
      <text class="title">Rattail array helpers</text>
      <text class="desc">
        This page lives in the main package and imports functions from rattail.
      </text>
    </view>

    <view class="card">
      <text class="label">source</text>
      <text class="code">{{ sourceText }}</text>
    </view>

    <button class="button" @click="goSubPackage">
      Open sub package rattail demo
    </button>
  </view>
</template>

<script setup>
import { computed } from 'vue'
import { isString } from 'rattail'

const numbers = [1, 2, 2, 3, 4, 4, 5, 6]

const sourceText = computed(() => isString(numbers) ? 'A string' : 'Not a string')

function goSubPackage() {
  uni.navigateTo({
    url: '/pages/sub/rattail/index',
  })
}
</script>

// 这里并没有添加 scoped
<style>
.page {
  min-height: 100vh;
  padding: 40rpx 32rpx;
  background: linear-gradient(135deg, #fff7e6 0%, #e9f7ef 48%, #e8f1ff 100%);
  box-sizing: border-box;
}

.hero {
  display: flex;
  flex-direction: column;
  gap: 14rpx;
  margin-bottom: 28rpx;
}

.eyebrow {
  color: #2f6f55;
  font-size: 24rpx;
  font-weight: 700;
  letter-spacing: 4rpx;
  text-transform: uppercase;
}

.title {
  color: #16231e;
  font-size: 44rpx;
  font-weight: 800;
}

.desc {
  color: #52615b;
  font-size: 28rpx;
  line-height: 1.6;
}

.card {
  padding: 28rpx;
  margin-bottom: 22rpx;
  border: 2rpx solid rgba(22, 35, 30, 0.08);
  border-radius: 28rpx;
  background: rgba(255, 255, 255, 0.75);
  box-shadow: 0 18rpx 40rpx rgba(47, 111, 85, 0.1);
}

.label {
  display: block;
  margin-bottom: 14rpx;
  color: #2f6f55;
  font-size: 24rpx;
  font-weight: 700;
}

.code {
  color: #16231e;
  font-family: Menlo, Consolas, monospace;
  font-size: 24rpx;
  line-height: 1.6;
  white-space: pre-wrap;
}

.button {
  margin-top: 18rpx;
  color: #ffffff;
  background: #1f7a5a;
  border-radius: 999rpx;
  font-weight: 700;
}
</style>

解决方案

如果是 cli 项目,找到 node_modules/@dcloudio/uni-h5-vite/dist/index.js 文件,注释 uniCssScopedPlugin

如果是 hbuilderx 项目,找到 /Applications/HBuilderX.app/Contents/HBuilderX/plugins/uniapp-cli-vite/node_modules/@dcloudio/uni-h5-vite/dist/index.js 文件

运行效果

写在最后

感觉您耐心看完这篇文章,希望您能喜欢。这里是《前端毕业班》,前端开发者的自救互助小组。在 AI 与不确定性并存的时代,我们一起看清焦虑,聊技术、聊趋势,也聊前端还能走多远,走去哪。

相关推荐
yingyima2 分钟前
Nginx 配置速查手册:核心语法与实战案例
前端
梨子同志4 分钟前
开发工具
前端·后端
像我这样帅的人丶你还8 分钟前
Java 后端详解(六):Maven 与本地开发指南
前端·后端
触底反弹9 分钟前
🎲 纯 CSS 搞定 3D 旋转立方体?还附赠一个「天坑」解决方案!
前端·css·html
盗德13 分钟前
LangChain.js 中文开发手册(记录)
前端
༄沐࿆风࿆࿆1 小时前
JavaScript函数完全指南:从基础语法到闭包原理与应用实战
开发语言·javascript
Geek-Chow1 小时前
微服务认证与授权:01 — 概念
java·前端·数据库
finyouIT1 小时前
锚点实现了点击导航平滑滚动到页面指定位置的三种方法
javascript·css
狂炫冰美式1 小时前
凌晨睡不着,我给台风巴威写了个追踪网站
前端·后端·github
雪隐2 小时前
用Flutter做背单词APP-01服务器?不存在的,我家里就有
前端·人工智能·后端