vue.js - 在道具更改后更新由道具制作的反应对象
问题描述
我有以下组件:
<template>
<vote-buttons :score="commentRef.score"
@update-score="updateScore">
</vote-buttons>
</template>
<script>
props: {
comment: {type: Object}
},
setup(props) {
const commentRef = ref(props.comment);
const updateScore = (value) => {
commentRef.value.score = value;
}
}
</script>
问题是当父组件再次循环时..
<comment v-for="comment in comments" :comment="comment">
</comment>
然后 prop 有新数据,但commentRef
没有更新。道具更改后如何重新触发反应性对象创建?谢谢
解决方案
代码中有一些问题:
您应该在父组件中添加一个键:(这里猜测您在评论对象中有一个唯一的 id)
<Comment
v-for="comment in comments"
:comment="comment"
:key="comment.id"></Comment>
将注释定义为反应性对象,子不需要为道具引用,下面给出了一个类似的示例,但与您的代码不完全相同:
父组件:
<template>
<Comment v-for="comment in comments" :comment="comment" :key="comment.id"></Comment>
<button @click="addCmt">addCmt</button>
</template>
<script>
import Comment from "./components/Comment";
import {reactive} from "vue";
export default {
name: "Params",
setup() {
const comments = reactive([{id: 1, name: 'a'}, {id: 6, name: 'c'}]);
function addCmt() {
comments.unshift({id: comments.length + 10, name: 'k'});
}
return {
comments,
addCmt
}
},
components: {Comment}
}
</script>
评论组件:
<template>
<div>comments {{ comment.id }}</div>
</template>
<script>
export default {
name: "Comment",
props: ['comment'],
setup(props, ctx) {
const comment = props.comment;
return {comment};
}
}
</script>
推荐阅读
- algorithm - 背包问题 - 从 5 组中选择最佳可能的项目组合,包括每组 1 项
- spotfire - 在spotfire中链接两个表
- google-cloud-platform - 谷歌云平台服务帐号无法访问项目
- javascript - JS 分数数组:如何在分数数组中添加一个数字并剔除较小的数字?
- arrays - 在 Google 表格中创建一列中的所有值与另一列中的所有值的组合列表
- neo4j - 密码查询:相关节点不同
- javascript - 从数据库加载数据后如何使动态表单自行刷新
- c++ - 在命令提示符下在我的 g++ (5.1.0) 编译器上使用 unordered_map 显示错误
- javascript - 如何为 ASP.NET Menu 和 MenuItem 控件包含 onfocus 和 onblur 事件
- angular - 如果我知道它的标题字段值而不是 id,我可以向现有文档添加新字段吗?