uni-app vue3组合式setup语法,子组件不能 watch监听 prop 变化
uni-app vue3组合式setup语法,子组件不能 watch监听 prop 变化
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
PC | macOS High Sierra | CLI |
浏览器 | Chrome | |
CLI | 3.0.0-alpha-3040820220426002 |
示例代码:
<script setup lang="ts">
import { watch, watchEffect } from 'Vue'
type IListObj = Record<string, string | number | Array<IListObj>>
interface Props {
modelValue: string | number | string[] | number[],
list: Array<IListObj>
}
const props = withDefaults(defineProps<Props>(), {
modelValue: '',
list() {
return []
}
})
watch(() => props, (val) => console.log(val))
watch(() => props.list, (val) => console.log(val))
watchEffect(() => {
console.log('modelValue: ', props.modelValue)
console.log('list: ', props.list)
})
<child v-model="xx" :list="list">
当 xx
或者 list
变化时,子组件中的 watch
和 watchEffect
都不会触发
操作步骤:
更改 xx
或者 list
的值,子组件中的 watch
和 watchEffect
都不会触发
预期结果:
watch
和 watchEffect
触发
实际结果:
没有触发
bug描述:
vue3 setup 子组件不能 watch
监听 prop
变化
同样遇到问题了。我h5是好的,小程序不行
奥,我是因为 prop 名称的格式问题, 不要用 :data-source=“xx”, 用驼峰的:dataSource=“xx”, 小程序就表现一致了
在 uni-app
中使用 Vue 3
的组合式 API(setup
语法)时,如果你在子组件中无法通过 watch
监听 props
的变化,可能是由于以下几个原因导致的。下面我将详细解释可能的原因以及如何解决这个问题。
1. 确保 props
被正确传递
首先,确保父组件正确地将 props
传递给子组件。如果 props
没有正确传递,子组件自然无法监听到变化。
<!-- 父组件 -->
<template>
<ChildComponent :someProp="someValue" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const someValue = ref('initial value');
</script>
2. 在子组件中正确声明 props
在子组件中,确保你正确地声明了 props
。props
应该在 defineProps
中声明。
<!-- 子组件 -->
<template>
<div>{{ someProp }}</div>
</template>
<script setup>
import { watch } from 'vue';
// 声明 props
const props = defineProps({
someProp: {
type: String,
required: true
}
});
// 监听 props 变化
watch(() => props.someProp, (newVal, oldVal) => {
console.log('someProp changed:', newVal, oldVal);
});
</script>
3. 使用 watch
监听 props
在 setup
函数中,你可以使用 watch
来监听 props
的变化。注意,watch
的第一个参数应该是一个返回 props
值的函数。
watch(() => props.someProp, (newVal, oldVal) => {
console.log('someProp changed:', newVal, oldVal);
});
4. 确保 props
是可变的
如果你传递的 props
是一个不可变的值(例如,一个基本类型的值),那么 watch
将无法检测到变化。确保你传递的是一个可变的值,例如 ref
或 reactive
对象。
5. 检查 uni-app
的版本
确保你使用的 uni-app
版本支持 Vue 3
的组合式 API。如果你使用的是较旧的版本,可能需要升级 uni-app
。
6. 使用 onBeforeUpdate
生命周期钩子
如果你仍然无法通过 watch
监听 props
的变化,可以尝试使用 onBeforeUpdate
生命周期钩子来检测 props
的变化。
import { onBeforeUpdate } from 'vue';
onBeforeUpdate(() => {
console.log('props updated:', props.someProp);
});
7. 检查 props
的默认值
如果你为 props
设置了默认值,确保默认值不会影响 watch
的监听。
const props = defineProps({
someProp: {
type: String,
default: 'default value'
}
});
8. 使用 computed
属性
如果你需要基于 props
计算一些值,可以使用 computed
属性。
import { computed } from 'vue';
const computedProp = computed(() => props.someProp.toUpperCase());