首页 > 解决方案 > 在道具更改后更新由道具制作的反应对象

问题描述

我有以下组件:

<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没有更新。道具更改后如何重新触发反应性对象创建?谢谢

标签: vue.js

解决方案


代码中有一些问题:

您应该在父组件中添加一个键:(这里猜测您在评论对象中有一个唯一的 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>

推荐阅读