uni-app vue3 在 v-if 中使用 wxs 报错

uni-app vue3 在 v-if 中使用 wxs 报错

类别 信息
产品分类 uniapp/小程序/微信
PC开发环境 Windows
操作系统版本 Windows 10 20H2
开发工具 HBuilderX
工具版本 3.3.0
第三方工具 1.05.2109131
基础库版本 2.21.0
项目创建方式 HBuilderX

操作步骤:

<template>  
    <view>  
        <view v-if="test.aa()">123</view>  
    </view>  
</template>  
<script module="test" lang="wxs">  
    function aa() {  
        return true  
    }  
    module.exports = {  
        aa: aa  
    }  
</script>

预期结果:

  • 正常运行

实际结果:

  • 运行时报错
  • ReferenceError: test is not defined

bug描述:

  • vue3 在 v-if 中使用 wxs 报错,vue2 正常

更多关于uni-app vue3 在 v-if 中使用 wxs 报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app vue3 在 v-if 中使用 wxs 报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在 uni-app 的 Vue3 版本中,v-if 指令内直接调用 WXS 模块函数确实会报错,因为 Vue3 的编译方式与 Vue2 不同,导致模板中的 WXS 模块引用在编译时未能正确解析。

原因分析: Vue3 使用了不同的编译策略,模板中的 WXS 模块(如 test.aa())在编译阶段可能未被正确处理,导致运行时 test 未定义。而 Vue2 的编译方式兼容了此用法。

解决方案:

  1. 改用 wx:if
    在小程序环境中,优先使用原生的 wx:if 替代 v-if,因为 WXS 模块在原生指令中能正确识别:

    <view wx:if="{{test.aa()}}">123</view>
    
  2. 通过计算属性中转
    在 Vue3 的 script setup 中,将 WXS 函数的调用结果转为计算属性,再在 v-if 中使用:

    <template>
      <view v-if="showText">123</view>
    </template>
    <script setup>
    import { ref } from 'vue'
    const showText = ref(true) // 通过逻辑或WXS结果赋值
    </script>
    <script module="test" lang="wxs">
    function aa() { return true }
    module.exports = { aa: aa }
    </script>
回到顶部