如题
微信小程序中,父页面通过Prop传递对象item给组件A,子页面修改后item某个字段后,父页面中无变化
在H5,App中父页面中item的字段值都是跟随变化的,
在微信小城中,父页面中一直无变化,在子页面也父页面中都使用this.$forceUpdate(),问题仍然未解决。
该怎么解决呢?
![u***@yeah.net](https://img-cdn-tc.dcloud.net.cn/account/identicon/85d386a38ed2f6a7cac9524b0fa0d2bd.png)
- 发布:2024-06-04 17:28
- 更新:2024-06-05 09:16
- 阅读:178
![爱豆豆](http://img-cdn-tc.dcloud.net.cn/uploads/avatar/001/20/55/59_avatar_mid.jpg?v=0)
![](http://img-cdn-tc.dcloud.net.cn/static/common/sponsor-1.png)
![](http://img-cdn-tc.dcloud.net.cn/static/common/sponsor-count-3.png)
爱豆豆 - 办法总比困难多
子组件 最好不要直接修改Props接收到的值
推荐你使用emit发出一个事件 在父组件/页面 里修改这个变量的内容 来发生改变
父组件/页面
<template>
<view>
<template v-for="(item,index) in list">
<testItem :item="item" :i="index" @setItem="setItem"></testItem>
</template>
</view>
</template>
<script setup>
import testItem from './components/test-item.vue'
import {ref} from 'vue'
let list = ref([{
title:111
},{
title:222
}])
const setItem = (items,index) => {
list.value[index].title = items
}
</script>
子组件 test-item
<template>
<view>
<text>第{{i}}个子组件------{{item.title}}</text>
<button @tap="tapItem">修改item的title</button>
</view>
</template>
<script setup>
let props = defineProps({
item: {
type: Object,
default: {}
},
i: {
type: Number,
default: null
},
})
const emit = defineEmits(['setItem'])
const tapItem = () => {
emit('setItem',props.item.title+1,props.i)
}
</script>
![u***@yeah.net](https://img-cdn-tc.dcloud.net.cn/account/identicon/85d386a38ed2f6a7cac9524b0fa0d2bd.png)
u***@yeah.net (作者)
经过尝试,我使用了两种方法解决这个问题:
1.按照1楼的方法:在子组件中通过this.$emit(),把数据发送到父页面中,在父页面中再更新
- 猜测小程序中prop传进去后,组件内部进行了一次深拷贝,组件内部的item和父页面中的item已经没有任何关系(这和APP、H5有本质区别)。再父页面中当需要用到最新数据时使用this.$refs.test.item.title ,这总方法比第一种可以精简代码
u***@yeah.net (作者)
按照你的建议,问题解决了。 但是,uniapp 号称一套代码多端部署,为什么在App和H5模式下正常的逻辑,在微信小程序中不正常了呢,是小程序做了什么限制吗,能否给深入一点的原理性的解释?
2024-06-05 08:55
爱豆豆
回复 u***@yeah.net: 不是说做了什么限制 而是因为单向数据流的原则 是不能直接在子组件中修改父级传递过来的数据的 所以想要修改props数据 就要通过子组件事件传递 给父级组件 然后由父组件修改 props绑定的数据 就跟我上面的示例代码一样
2024-06-05 09:50