uni-app nvue 页面,动态改变父级class样式时子元素样式不改变
uni-app nvue 页面,动态改变父级class样式时子元素样式不改变
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | Windows 10 专业版 22H2 | HBuilderX |
产品分类:uniapp/App
PC开发环境操作系统:Windows
PC开发环境操作系统版本号:Windows 10 专业版 22H2
HBuilderX类型:正式
HBuilderX版本号:3.96
手机系统:Android
手机系统版本号:Android 8.1
手机厂商:华为
手机机型:BLN-AL40
页面类型:nvue
vue版本:vue3
打包方式:云端
项目创建方式:HBuilderX
示例代码:
``` html
<template>
<view class="style" :class="[index == 1 ? ' on':'']" @click="click">
<text class="text">父级class改变时候, 我要改变颜色</text>
<text class="text">父级class改变时候, 我要改变颜色</text>
</view>
</template>
<script setup>
import {
ref
} from 'vue';
const index = ref(0)
const click = () => {
index.value = index.value == 1 ? 0 : 1
}
</script>
<style lang="scss">
.style {
background-color: #fff;
.text {
color: #000;
}
}
.on {
background-color: red;
.text {
color: #fff;
}
}
</style>
操作步骤: 复现步骤在代码示例
预期结果: 改变父级样式、 同时改变子元素样式
实际结果: 改变了父级样式、 子元素样式没改变
bug描述: 改变父级class ,也想改变当前元素的样式, 但目前 只能改变父级样式、 子集样式不能改变 请问有什么解决方案么?
试试
<template>
<view :class="[index == 1 ? ’ on’:‘style’]" @click=“click”>
<text :key="key" class="text">父级class改变时候, 我要改变颜色</text>
<text class="text">父级class改变时候, 我要改变颜色</text>
</view>
</template>
感谢 可以了
如果是循环出来的元素、 就会出现所有元素都刷新一遍的问题
回复 新新新: 那肯定啊。。看你啥需求,要循环的话,就搞个动态的class或者style
如果不行、 那有什么代替方案么?
在 uni-app
的 nvue
页面中,动态改变父级元素的 class
样式时,子元素的样式不改变,可能是由于 nvue
的渲染机制与 vue
页面有所不同。nvue
是基于 Weex
的原生渲染引擎,其样式处理和 CSS
的解析方式与 Web
有所不同。
以下是一些可能的原因和解决方案:
1. 样式继承问题
nvue
中的样式继承机制与 Web
不同,某些样式属性可能不会自动继承到子元素。你可以尝试直接在子元素上应用样式,而不是依赖父元素的样式继承。
<template>
<view :class="parentClass">
<text :class="childClass">子元素</text>
</view>
</template>
<script>
export default {
data() {
return {
parentClass: 'parent-style',
childClass: 'child-style'
};
}
};
</script>
<style>
.parent-style {
background-color: red;
}
.child-style {
color: white;
}
</style>
2. 样式作用域
nvue
中的样式作用域可能与 Web
不同,确保你的样式选择器正确匹配到子元素。你可以使用更具体的选择器来确保样式应用到子元素。
.parent-style .child-style {
color: white;
}
3. 动态样式绑定
如果你需要动态改变子元素的样式,可以直接在子元素上绑定样式,而不是依赖父元素的 class
变化。
<template>
<view :class="parentClass">
<text :style="childStyle">子元素</text>
</view>
</template>
<script>
export default {
data() {
return {
parentClass: 'parent-style',
childStyle: {
color: 'white'
}
};
}
};
</script>
<style>
.parent-style {
background-color: red;
}
</style>
4. 强制刷新样式
如果上述方法仍然无效,可以尝试通过强制刷新组件来重新应用样式。例如,通过 key
属性强制重新渲染组件。
<template>
<view :class="parentClass" :key="parentClass">
<text>子元素</text>
</view>
</template>
<script>
export default {
data() {
return {
parentClass: 'parent-style'
};
}
};
</script>
<style>
.parent-style {
background-color: red;
}
</style>
5. 检查 nvue
的样式支持
nvue
并不支持所有的 CSS
属性,某些样式属性可能无法正常工作。你可以查阅 uni-app
官方文档,确认你使用的样式属性在 nvue
中是否被支持。
6. 使用 scoped
样式
如果你在 nvue
中使用了 scoped
样式,可能会导致样式无法正确应用到子元素。你可以尝试移除 scoped
,或者使用全局样式。
<style scoped>
/* 可能会影响子元素的样式 */
</style>
<style>
/* 全局样式 */
</style>