Vue v-如果不更新 [英] Vue v-if not updating

查看:28
本文介绍了Vue v-如果不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 Vue 模板的一部分:

Here's a part of my Vue template:

<ul>
   <li v-for="friend in user.friends">
       <span v-if="checkIfNew(friend.id)"> ... </span>
   </li>
</ul>

基本上,朋友是一个对象数组,如果我们有来自其中任何一个的新消息,我想显示 span 元素.这就是 checkIfNew() 所做的.它检查朋友的 id 是否在 unreadIds 数组中(它包含朋友的 id,谁发送了消息)

Basically, friends is an array of objects, and I want to display the span element, if we have new messages from any of them. That's what checkIfNew() does. It checks whether the friend's id is in the unreadIds array (it contains ids of friends, who sent a message)

这个数组正在以不同的方法更新,但问题是:v-if 对更改没有反应.

This array is being updated in a different method, but, here's the problem: v-if doesn't react to the changes.

这是脚本部分的一部分:

Here's a part of the script section:

data(){
   return {
      unreadIds: []
   }
},
methods:{
   checkIfNew(id){
      if(id in this.unreadIds) return true
      else return false
   }
},
computed:{
    user(){
      return this.$store.getters.user;
    }
}

有人知道我做错了什么吗?

Does anyone have any ideas what am I doing wrong?

推荐答案

我要试一试 - 有人早些时候发布了这个并删除了它.您需要 checkIfNew() 成为计算而不是模板中的反应性方法.

I'll have a stab at it - someone posted this earlier and deleted it. You need checkIfNew() to be a computed not a method for reactivity in the template.

因为需要传入id,所以计算需要返回一个函数.

Since you need to pass in the id, the computed needs to return a function.

data(){
   return {
      unreadIds: []
   }
},
computed:{
    user(){
      return this.$store.getters.user;
    },
   checkIfNew(){
      return (id) => {
        return this.unreadIds.includes(id);
      }
   }
}

正如 David Weldon 所说,理想情况下,您应该一成不变地更改数组 - 可能是为什么 ohgodwhy 问了最初的问题.

As David Weldon says, you should ideally change the array immutably - and probably why ohgodwhy asked the original question.

这篇关于Vue v-如果不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆