vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue父子组件数据更新

vue3父子组件数据更新不及时的问题解决方案

作者:月伤59

文章介绍了在使用props向子组件传值时,如果直接赋值不会导致子组件数据更新的问题,文章提供了解决方案,通过在父组件中使用 nextTick确保数据变化后再调用子组件中的接口,从而保证数据同步更新,感兴趣的朋友跟随小编一起看看吧

使用props向子组件传值时,使用如下方式会导致组件不更新数据:

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的数据不会发生变化,因为数据是单向数据流,这里的赋值只会赋值一次。

通过如下方式解决:

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中调用子组件中获取数据的接口,保证数据变化完后调用接口:

nextTick(() => {
	children.getData();
});

到此这篇关于vue3父子组件数据更新不及时的问题解决方案的文章就介绍到这了,更多相关vue3父子组件数据更新内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文