uni-app页面使用 skyline 模式渲染时 styleIsolation 配置废弃导致样式无法共享到组件(uniapp+vue3+ts 项目)

发布于 1周前 作者 vueper 来自 Uni-App

uni-app页面使用 skyline 模式渲染时 styleIsolation 配置废弃导致样式无法共享到组件(uniapp+vue3+ts 项目)

开发环境 版本号 项目创建方式
Windows Win11 CLI

操作步骤:

给 webview 渲染的项目的单个页面升级成 skyline 渲染。

"lazyCodeLoading": "requiredComponents",  
"rendererOptions": {  
  "skyline": {  
    "defaultDisplayBlock": true,  
    "defaultContentBox": true  
  }  
},
"renderer": "skyline",  
"componentFramework": "glass-easel",  
"disableScroll": true,  
"navigationStyle": "custom",

这个页面给标签设置一些全局样式如 box-sizing: border-box;,编译项目,开发工具开启 skyline 渲染调试。

预期结果:

样式可以作用于页面中的组件。

实际结果:

样式无法作用于页面中的组件。

bug描述:

页面使用 skyline 模式渲染时,如下代码不起作用:

<script lang="ts">  
import { defineComponent } from 'vue'  

export default defineComponent({  
  options: {  
    styleIsolation: 'shared',  
  },  
})  
</script>

开发工具控制台提示

Dynamic `styleIsolation` option in component definition of "pages/index/index" have been deprecated, and will NOT take effect in glass-easel. Consider migrating this option to component static config (pages/index/index.json) by adding `{ "styleIsolation": "shared" }`.

2 回复

uni-app 中使用 skyline 模式渲染时,styleIsolation 配置被废弃,这可能导致页面样式无法共享到组件。为了解决这个问题,你可以尝试以下几种方法:

1. 使用 globalStyle 在全局共享样式

你可以在 App.vue 中定义全局样式,这样所有的页面和组件都可以共享这些样式。例如:

<!-- App.vue -->
<template>
  <view class="global-style">
    <!-- 其他内容 -->
  </view>
</template>

<style>
.global-style {
  font-size: 16px;
  color: #333;
}
</style>

然后在页面或组件中直接使用这些全局样式:

<!-- 页面或组件 -->
<template>
  <view class="global-style">
    <!-- 页面或组件内容 -->
  </view>
</template>

2. 使用 scoped 样式

如果你希望样式只在当前组件中生效,可以使用 scoped 样式。这样可以避免样式污染其他组件:

<template>
  <view class="my-component">
    <!-- 组件内容 -->
  </view>
</template>

<style scoped>
.my-component {
  font-size: 14px;
  color: #666;
}
</style>

3. 使用 CSS Modules

CSS Modules 是另一种处理样式作用域的方式,它可以确保样式只在当前组件中生效。你可以在 vue 文件中这样使用:

<template>
  <view :class="$style.myComponent">
    <!-- 组件内容 -->
  </view>
</template>

<style module>
.myComponent {
  font-size: 14px;
  color: #666;
}
</style>

4. 使用 uni.scss 文件

你可以在 uni.scss 文件中定义全局的 SCSS 变量和混合宏,然后在各个组件中引用这些变量和混合宏:

/* uni.scss */
$primary-color: #007bff;

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

然后在组件中使用:

<template>
  <view class="my-component">
    <!-- 组件内容 -->
  </view>
</template>

<style lang="scss">
[@import](/user/import) '@/uni.scss';

.my-component {
  color: $primary-color;
  @include flex-center;
}
</style>

5. 手动管理样式

如果以上方法都无法满足你的需求,你可以手动管理样式,将需要共享的样式提取到一个单独的 CSSSCSS 文件中,然后在需要的组件中引入:

/* shared-styles.css */
.shared-style {
  font-size: 16px;
  color: #333;
}

然后在组件中引入:

<template>
  <view class="shared-style">
    <!-- 组件内容 -->
  </view>
</template>

<style>
[@import](/user/import) './shared-styles.css';
</style>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!