Nuxt JS如何在async fetch()方法内使用新数据更新props
问题解答
不可以。Vue遵循单向数据流规则,props是父组件传递给子组件的只读属性,子组件不允许直接修改props,无论在哪个生命周期/方法内直接修改props,都会在开发环境抛出警告,且父组件后续更新时子组件的修改会被覆盖,造成数据混乱。
你原有代码中直接对this.products执行push操作的写法,因为数组是引用类型,会直接修改父组件的源数据,虽然能临时生效,但不符合Vue的数据流规范,极易出现数据不一致的问题,非常不推荐。
根据你的使用场景,可选择以下两种合规方案实现需求:
场景1:修改后的数据仅需在当前子组件使用
不需要同步给父组件的情况下,可在子组件内声明本地响应式变量,拷贝props的值作为初始值,后续直接修改本地变量即可:
props: { products: { type: Array, required:true } }, data() { return { // 浅拷贝数组作为本地初始值,若数组元素为对象可按需用深拷贝 localProducts: [...this.products] } }, async fetch() { let data = this.localProducts // 你的数据处理逻辑 // 示例:拿到接口返回的新数据后更新本地变量 const newData = await 你的接口请求逻辑() this.localProducts.push(newData) }
场景2:修改后的数据需要同步给父组件
通过自定义事件通知父组件修改源数据,父组件更新后props会自动同步到子组件:
子组件代码
props: { products: { type: Array, required:true } }, async fetch() { // 你的数据处理逻辑 const newData = await 你的接口请求逻辑() // 抛出更新事件,将更新后的全量数据传给父组件 this.$emit('update:products', [...this.products, newData]) }, methods: { updateProducts(newdata) { this.$emit('update:products', [...this.products, newdata]) } }
父组件代码
<template> <!-- 监听子组件的更新事件,修改父组件的源数据 --> <ChildComponent :products="parentProducts" @update:products="parentProducts = $event" /> </template> <script> export default { data() { return { parentProducts: [] } } } </script>
内容的提问来源于stack exchange,提问作者francky
相关产品推荐
相关产品推荐

