首页 > 解决方案 > 谁来解决这个问题:在vuejs中更新一个chiled组件更新所有其他childeren?

问题描述

我想更新喜欢的特定评论这是父组件 Commnet.vue

<template>
    <v-list class="list" color="white" three-line>
      <template v-for="cmnt in comments" class="mb-2">
        <v-card color="transparent" class=" text-no-wrap" :key="cmnt._id">
          <v-list-item class="item" :key="cmnt._id">
            <v-list-item-avatar>
              <v-img :src="cmnt.author.image"></v-img>
            </v-list-item-avatar>
            <v-list-item-content class="black--text">
              <v-list-item-title>{{
                cmnt.author.first_name + " " + cmnt.author.last_name
              }}</v-list-item-title>
              <v-list-item-subtitle class="black--text" v-html="cmnt.comment">
                {{ cmnt.comment }}
              </v-list-item-subtitle>
            </v-list-item-content>
            <v-card class="like-count">
              <v-icon color="blue">mdi-thumb-up </v-icon>
              <Likes :_id="cmnt._id"/>
            </v-card>
          </v-list-item>  
        </v-card>

        <v-card
          :key="cmnt._id"
          outlined="true"
          color="transparent"
          class="ml-6"
        >
</template>

这是评论组件中的子组件,它拥有自己的状态,与父组件完全分离。

喜欢.vue

<template>
     <div>
       <v-card >

       </v-card>
       {{likes.length}}
     </div>

</template>

<script>
import axios from "axios";

import io from "socket.io-client";
export default {
    name:"Likes",
    created:async function(){
      axios.get(`comment/${this._id}`)
      .then(results=>{
        if (results.data){
            this.likes =results.data;
        }
      })
      .catch(err=> console.log(err));

      let url = "";
    if (process.env.NODE_ENV === "production") {
      url = "/";
    } else {
      url = "http://localhost:5000";
    }
    this.socket = io(url);

 this.socket.on("receive-like",async  (data)=>{
      console.log(data)
      this.new_like= data;
      console.log(this.new_like)
      const el = this.likes.find(el => el._id === this.new_like._id)
    if (el){
      const index = this.likes.indexOf(el);
      this.$forceUpdate()

     return this.likes.splice(index,1)
    }else{
      this.likes.push(this.new_like);
      console.log(this.likes)
      this.$forceUpdate()
    }

    })

    },
    mounted:async function(){

    },
    props:{
      _id:{
        type: String
      }
    },
    data:()=>({
      user:{},
      likes:[],
      new_like:{}
    }),
computed:{
 
},
    }
</script>

因此,当单击新的点赞对象时,会被推送到相关评论的点赞数组中,但所有评论的点赞都会更新为点赞。

标签: vue.js

解决方案


如果有人想知道我刚刚添加了新的类似对象条件 if(data.comment._id === this._id)


推荐阅读