uni-app nvue + vue3 动态类名不生效(nvue + vue2可以)

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

uni-app nvue + vue3 动态类名不生效(nvue + vue2可以)

开发环境 版本号 项目创建方式
Mac 12.7.3 HBuilderX

测试过的手机

小米 ios模拟器(13pro)

示例代码:

<template>  
    <view class="content">  
        <image class="logo" src="/static/logo.png"></image>  
        <view class="box" :class="[a ? 'active' : '']" @click="boxClick"></view>  
    </view>  
</template>  

<script setup>  
    import {ref} from 'vue'  
    const a = ref(false)  
    const boxClick = () => a.value = !a.value  
</script>  

<style>  
    .content {  
        width: 750rpx;  
        height: 750rpx;  
    }  
    .box {  
        height: 400rpx;  
        width: 400rpx;  
        background-color: red;  
    }  
    .active {  
        background-color: yellow;  
    }  
</style>  

操作步骤:

预期结果:

动态类名生效

实际结果:

动态类名不生效

bug描述:

动态类名不生效 随便一个nvue + vue3的项目就能复现


6 回复
<template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="box" :class="[a ? 'active' : '']" @click="boxClick"></view> </view> </template> <script> export default { data() { return { a: false } }, methods: { boxClick() { this.a = !this.a } } } </script> <style> .box { height: 400rpx; width: 400rpx; background-color: red; } .active { background-color: yellow; } </style>

这是vue2,是可以的


const boxClick = () => a.value = !a.value

这个忘了删了,其实就是不行

好同志,你试试行不行

回复 YZL_zyzl: 应该是bug,数组写法改成对象写法吧

uni-app 中使用 nvueVue3 时,动态类名不生效的问题可能是由于 nvueVue3 的兼容性问题,或者是 nvue 本身的限制。以下是一些可能的原因和解决方案:

1. 检查语法

确保你在 Vue3 中的动态类名语法是正确的。Vue3 中动态类名的语法与 Vue2 略有不同。

<template>
  <view :class="{'active': isActive, 'disabled': isDisabled}">内容</view>
</template>

<script setup>
import { ref } from 'vue';

const isActive = ref(true);
const isDisabled = ref(false);
</script>

2. 使用 classstyle 绑定

nvue 中,动态类名和样式的绑定可能需要使用 classstyle 绑定的方式。

<template>
  <view :class="classObject">内容</view>
</template>

<script setup>
import { ref, computed } from 'vue';

const isActive = ref(true);
const isDisabled = ref(false);

const classObject = computed(() => ({
  active: isActive.value,
  disabled: isDisabled.value
}));
</script>

3. 使用 style 绑定

如果动态类名不生效,可以尝试使用 style 绑定来动态设置样式。

<template>
  <view :style="styleObject">内容</view>
</template>

<script setup>
import { ref, computed } from 'vue';

const isActive = ref(true);
const isDisabled = ref(false);

const styleObject = computed(() => ({
  color: isActive.value ? 'red' : 'black',
  backgroundColor: isDisabled.value ? 'gray' : 'white'
}));
</script>

4. 检查 nvue 版本

确保你使用的是最新版本的 uni-appnvue,因为某些问题可能在新版本中已经修复。

5. 使用 Vue2 语法

如果你发现 Vue3 的语法在 nvue 中不兼容,可以尝试回退到 Vue2 的语法。

<template>
  <view :class="{'active': isActive, 'disabled': isDisabled}">内容</view>
</template>

<script>
export default {
  data() {
    return {
      isActive: true,
      isDisabled: false
    };
  }
};
</script>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!