vue.js - 谁来解决这个问题:在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>
因此,当单击新的点赞对象时,会被推送到相关评论的点赞数组中,但所有评论的点赞都会更新为点赞。
解决方案
如果有人想知道我刚刚添加了新的类似对象条件 if(data.comment._id === this._id)
推荐阅读
- azure - Azure App service resource group on Sandbox. Created for learning does not allow Free Service plans
- blazemeter - 将 Taurus 测试指定为 Blazemeter 功能测试
- matplotlib - 更改子图上刻度标签的旋转
- python - Sympy 返回日志而不是 ln
- reactjs - setState 不会在 intervalRef 内更新
- azure - 使用内置策略时 Azure AD B2C“用户名或密码无效”
- python-3.x - “配额组'ReadGroup'的配额超出并限制'每100秒每个用户的读取请求'服务google api
- json - Azure Blob 的奇怪编码问题导致无法从 JSON 转换为对象
- android - ReactNative 中的可访问性标识符问题
- reactjs - 功能组件上的反应更新状态钩子不允许点符号