使用props向子组件传值时,使用如下方式会导致组件不更新数据:
javascript
const props = defineProps({
typeOne: {
type: Number,
default: 0
},
typeTwo: {
type: Number,
default: 0
}
});
const searchParams = ref({
typeOne: props.typeOne,
typeTwo: props.typeTwo
});
父组件中的typeOne和typeTwo发生变化时,searchParams的数据不会发生变化,因为数据是单向数据流,这里的赋值只会赋值一次。
通过如下方式解决:
javascript
const props = defineProps({
typeOne: {
type: Number,
default: 0
},
typeTwo: {
type: Number,
default: 0
}
});
const { typeOne, typeTwo } = toRefs(props);
const searchParams = ref({
typeOne: computed(() => typeOne.value),
typeTwo: computed(() => typeTwo.value)
});
这样写了之后,父组件数据发生变化时,子组件的searchParams中的数据就会跟着变化。
在父组件中要使用nextTick中调用子组件中获取数据的接口,保证数据变化完后调用接口:
javascript
nextTick(() => {
children.getData();
});