computed函数当中访问解构的props的行为与Vue官方不一致
computed函数当中访问解构的props的行为与Vue官方不一致
项目信息 | 详情 |
---|---|
产品分类 | uniapp/小程序/微信 |
PC开发环境操作系统 | Windows |
PC开发环境操作系统版本号 | Win11 |
第三方开发者工具版本号 | Nightly 1.06.2501162 |
基础库版本号 | 3.7.5 |
项目创建方式 | CLI |
CLI版本号 | latest |
操作步骤:
<script setup>
import { computed } from 'vue';
const { num } = defineProps(['num']);
const state = computed(() => (num % 2 === 0 ? 'even' : 'odd'));
</script>
<template>
<div>The number {{ num }} is {{ state }}</div>
</template>
预期结果:
预期能够在界面当中根据num的变化产生state的变化
实际结果:
并未产生响应式的计算
bug描述:
在官方的playground当中,组件1可以访问响应式num,但是在小程序uniapp里面这么写,不能够响应式
1 回复
这是一个uni-app与Vue3响应式处理差异的问题。在uni-app小程序环境中,直接解构props会导致响应式丢失,这与Vue3官方行为确实存在差异。
解决方案是避免直接解构props,改用props对象访问:
<script setup>
import { computed } from 'vue';
const props = defineProps(['num']);
const state = computed(() => (props.num % 2 === 0 ? 'even' : 'odd'));
</script>
或者使用toRefs保持响应式:
<script setup>
import { computed, toRefs } from 'vue';
const props = defineProps(['num']);
const { num } = toRefs(props);
const state = computed(() => (num.value % 2 === 0 ? 'even' : 'odd'));
</script>