【问题标题】:Vuefire Firebase update issuesVuefire Firebase 更新问题
【发布时间】:2017-09-11 00:05:59
【问题描述】:

我在从 VueFire 更新 Firebase 时遇到了一些问题。我正在尝试使用以下方法,但如果我将任何字段留空(这应该在设置中经常发生),它会对我大喊大叫。知道为什么如果 .update 使用空白字段会生气吗?

错误:未捕获的错误:Firebase.update 失败:第一个参数在属性“businesses.somebusiness.video”中包含未定义

updatePost(post) {
        postsRef.child(post['.key']).update({
          name: post.name,
          video: post.video,
          story: post.story,
          cover: post.cover,
          card: post.card
        })
      },

有一次我把上面的内容改写成这样:

updatePost: function (post) {
        const businesschildKey = post['.key'];
        delete post['.key'];
        /* Set the updated post value */
        this.$firebaseRefs.posts.child(businesschildKey).set(post)
      },

它的效果非常好,但删除键似乎会导致 Vue 中出现奇怪的排序问题。如果我能找到一种方法在留空时不让它出错,我宁愿坚持使用 top 方法。

【问题讨论】:

  • 很有趣,但是当我的属性可能是 ' ' 或具有取决于业务的值时,很难理解如何解决这个问题。
  • post.video 实际上是未定义的吗?试试video: post.video || null
  • || null 添加到末尾似乎已修复它。谢谢!那是做什么的?

标签: firebase firebase-realtime-database vue.js vuejs2 vuefire


【解决方案1】:

根据this post

当您将对象传递给 Firebase 时,属性的值可以 是一个值或null(在这种情况下,该属性将被删除)。他们 不能是undefined,这是您根据 错误。

您的错误消息表明post.video 的值为undefined。您可以使用逻辑或来提供一个后备值,如下所示:

  video: post.video || null,

这意味着只要 post.video 具有 false-y 值,表达式将计算为 null。不过,这可能会捕获空字符串或数字 0。更准确地说,您应该使用

  video: typeof post.video === 'undefined' ? null : post.video,

如果您需要对许多值进行此检查,您可以为其编写一个函数:

function nullIfUndefined(value) {
  return typeof value === 'undefined' ? null : value;
}

那么你的表情就是

  video: nullIfUndefined(post.video),

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 2021-11-22
    • 2020-10-12
    • 1970-01-01
    • 2018-01-31
    • 2023-03-11
    • 2017-10-17
    • 2018-01-13
    • 2017-05-25
    相关资源
    最近更新 更多