VueJS2组件间数据传递:父组件向子组件传递接口返回数据
Vue父组件向子组件传递大型JSON数据实现方案
1. 父组件侧:获取数据并通过Props传递
在父组件中完成接口请求,拿到服务器返回的res.data后存入响应式变量,再通过自定义属性传递给子组件:
<template> <div class="parent-component"> <!-- 通过`:large-data`绑定要传递的JSON数据 --> <child-comp :large-data="largeJsonData" /> </div> </template> <script> import ChildComp from './ChildComp.vue' // 引入子组件 export default { components: { ChildComp }, data() { return { largeJsonData: null // 存储接口返回的大型JSON数据 } }, mounted() { // 替换为你的真实接口请求逻辑 fetch('/api/large-data') .then(res => res.json()) .then(resData => { this.largeJsonData = resData }) .catch(err => console.error('请求失败:', err)) } } </script>
2. 子组件侧:接收Props并使用
子组件先声明接收的Props,之后即可在模板或方法中直接使用该数据:
方式一:Options API
<template> <div class="child-component"> <!-- 模板中直接使用props数据 --> <div>{{ largeData.someField }}</div> </div> </template> <script> export default { // 声明接收的props,可添加类型、必填校验和默认值 props: { largeData: { type: Object, required: true, default: () => ({}) } }, methods: { processData() { // 方法中通过this.largeData访问数据 console.log(this.largeData.detailList) } }, mounted() { this.processData() } } </script>
方式二:Composition API(Vue 3+)
<template> <div class="child-component"> <div>{{ largeData.someField }}</div> </div> </template> <script setup> // 声明接收的props const props = defineProps({ largeData: { type: Object, required: true, default: () => ({}) } }) // 脚本中通过props.largeData访问数据 console.log(props.largeData) function processData() { console.log(props.largeData.detailList) } </script>
额外提示
- 若JSON数据体积过大,建议在父组件中先做数据裁剪,只传递子组件需要的字段,减少性能开销
- 对于不可变的大型对象,可使用
Object.freeze()冻结数据,降低Vue响应式系统的资源消耗
内容的提问来源于stack exchange,提问作者voids Mark
相关产品推荐
相关产品推荐

