如何使用“Object.keys”函数在vue.js中列出firebase子节点的长度时防止出现错误?(How to prevent an error when listing the length of a firebase child node in vue.js using an “Object.keys” function?)

想象一下Vue.js应用程序,其中firebase中的数据结构将发展为如下形式:

item: {
  name: itemName,
  childOne: {
    subChildA: true,
    subChildB: true
  },
  childTwo: {
    subChildA: true,
    subChildB: true
  }
}

现在我有一个组件,我需要列出子节点的长度(这些子节点只会在稍后添加)。 我的第一个想法是简单地做到这一点,但这种策略是行不通的:

<tbody>
  <tr v-for="item in items" >
     <td>
        {{item.childOne.length - item.childTwo.length}}
     </td>
   </tr>
</tbody>

所以或者我得到这样的长度:

<tbody>
   <tr v-for="item in items" >
      <td>
         {{Object.keys(item.childOne).length - Object.keys(item.childTwo).length}}
      </td>
    </tr>
</tbody>

正如我所说的,我需要在创建项目的子项之前渲染该组件......这些子项节点后来通过Google Cloud Function有条件创建,所以我不可避免地从这个简单的结构开始:

item: {
  name: itemName,
}

...但在这个阶段,我收到一条错误消息:

TypeError:无法将未定义或null转换为Function.keys()处的对象

我在想,如果我使用第一种策略,vue.js足够聪明,可以避免此错误呈现组件,并且如果没有孩子,则不显示任何内容,但它无法获得长度

第二种策略在我添加孩子时非常有效,但它无法处理数据的初始缺失,甚至无法呈现视图

无论如何,当孩子节点不在那里时,使用第二种策略来防止这种错误?


Imagine a Vue.js app where the data structure in firebase will develop into something like this:

item: {
  name: itemName,
  childOne: {
    subChildA: true,
    subChildB: true
  },
  childTwo: {
    subChildA: true,
    subChildB: true
  }
}

Now I have a component where I need to list the length of the child nodes (these child nodes will only be added later). My first thought was to simply do this, but this strategy doesn't work:

<tbody>
  <tr v-for="item in items" >
     <td>
        {{item.childOne.length - item.childTwo.length}}
     </td>
   </tr>
</tbody>

So alternatively I got the length like this:

<tbody>
   <tr v-for="item in items" >
      <td>
         {{Object.keys(item.childOne).length - Object.keys(item.childTwo).length}}
      </td>
    </tr>
</tbody>

As I said I need to render that component before the item's children are created... These child nodes are later conditionally created through a Google Cloud Function so I inevitably start with this simple structure:

item: {
  name: itemName,
}

...but at this stage I get an error message:

TypeError: Cannot convert undefined or null to object at Function.keys ()

I am thinking that if I use the first strategy, vue.js is smart enough to avoid this error renders the component, and displays nothing if there are no children, but it can't get the lengths.

The second strategy works perfectly when I add the children but it can't deal with the initial absence of data and doesn't even render the view.

Is there anyway to prevent this error using the second strategy when the child nodes are not there yet?

2023-02-05 15:02

满意答案

您可以使用双管道运算符为item.childOneitem.childTwo实例提供默认的空对象。

改变这个:

{{Object.keys(item.childOne).length - Object.keys(item.childTwo).length}}

为此:

{{Object.keys(item.childOne || {}).length - Object.keys(item.childTwo || {}).length}}

小规模示例:

var test = {};
console.log(Object.keys(test.childOne || {}).length);

但是,您应该留意Vue无法检测到属性添加或删除。 根据文档

由于Vue在实例初始化期间执行getter / setter转换过程,因此数据对象中必须存在一个属性,以便Vue将其转换并使其处于被动状态。

根据您的具体用例,您可能需要在初始化过程中定义childOne或将其转换为数组,以便您可以利用Vue的观察数组变异方法


You can use the double pipe operator to supply a default empty object for instances where item.childOne or item.childTwo are not defined.

Change this:

{{Object.keys(item.childOne).length - Object.keys(item.childTwo).length}}

To this:

{{Object.keys(item.childOne || {}).length - Object.keys(item.childTwo || {}).length}}

Small scale example:

var test = {};
console.log(Object.keys(test.childOne || {}).length);

However, you should be mindful that Vue cannot detect property additions or deletions. As per the docs:

Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.

Depending on your exact use case, you may need to define childOne during initialization or convert it to an array so that you may take advantage of Vue's observed array mutation methods.

相关问答

更多

gulp-jscs Object.keys在非对象上调用(gulp-jscs Object.keys called on non-object)

如果jscs没有对您的.jscsrc的读取权限或者它不存在,这似乎就会发生。 这发生在我复制并从一个旧的git repro粘贴它后。 要解决这个问题,用文本编辑器打开文件并重新保存它,接受覆盖提示以及以'。'开头。 (例如.jscsrc)再次运行您的任务,它会完成。 This seems to happen if jscs doesn't have read access to your .jscsrc or if it doesn't exist. This happened to me aft...

在Vue.js App中初始化firebase 3.4.0(initialize firebase 3.4.0 in Vue.js App)

您导入Firebase但使用了firebase - 请注意资本F. 将导入更改为: import firebase from 'firebase'; 或者更改对Firebase.initializeApp或Firebase.database()所有调用 You imported Firebase but used firebase -- notice the capital F Either change the import to: import firebase from 'firebase'...

如何使用“Object.keys”函数在vue.js中列出firebase子节点的长度时防止出现错误?(How to prevent an error when listing the length of a firebase child node in vue.js using an “Object.keys” function?)

您可以使用双管道运算符为item.childOne或item.childTwo实例提供默认的空对象。 改变这个: {{Object.keys(item.childOne).length - Object.keys(item.childTwo).length}} 为此: {{Object.keys(item.childOne || {}).length - Object.keys(item.childTwo || {}).length}} 小规模示例: var test = {}; conso...

Object.keys(...)并不总是在IE中工作(Object.keys(…) not always work in IE)

你可以尝试自己动手: Object.keys = Object.keys || function keys(obj) { var ret = []; for (var prop in obj) if (obj.hasOwnProperty(prop)) ret.push(prop) return ret; } Apparently; IE 9 will in an intranet environment assume that all your intranet applicati...

从vue.js过滤器返回vue实例(Vue.js 2)(Return vue instance from vue.js filter (Vue.js 2))

就像Evan所说,过滤器应该是纯粹的 ,因此不能使用全局变量作为从外部数组获取值的关键。 因为副作用。 那么,我的脑海中有三种解决方案: 用方法替换过滤器。 使用vue-i18-n ,一个简单而强大的翻译模块 使用商店系统( vuex )为您提供吸气剂,并帮助您管理全球状态。 Personnaly我喜欢一起使用vuex和vue-i18-n。 通过这种方式,我可以集中我的数据和使用的语言。 我还可以使用商店以多种语言提供特定数据,让vue-i18-n关注项目中的所有字符串。 Like Evan sa...

Vue.js用于添加和编辑的相同表单(Vue.js same form for add and edit)

单击“ Edit按钮时,应将isEditing更改为true,并且应定义数据movie 。 editMovie: function (movie){ ... this.movie = Vue.util.extend({}, movie); // deep clone to prevent modify the original object this.isEditing = true; }, You should change the isEditing to true when t...

如何使用Object.keys()?(How to use Object.keys()?)

ES6 Object.keys(myData.customNotes).reduce((prev, curr) => { const date = curr; const concernedDate = myData.customNotes[curr].concernedDate; const numberNotes = myData.customNotes[curr].notesList.length; const notesList = myData.custo...

无法在vue.js 1.0和Laravel 5.1中处理错误(Can't get error handing in vue.js 1.0 and Laravel 5.1 to work)

我有同样的问题,而不是使用spark的开箱即用错误,我定义了自己的组件: <template> <div v-if="errors"> <div class="alert alert-danger" v-if="formattedErrors.length > 0"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> ...

Javascript:对象有键,但Object.keys返回空(Javascript: Object have keys, but Object.keys returns empty)

有3个因素可能导致您描述的一般行为。 在你的情况下,我认为这是第一个: 当您调用console.log(x) ,Chrome控制台将显示当时对象x的摘要。 但是, 展开对象时,将再次获取该值 。 自调用console.log()以来,您看到的详细对象可能已更改,更改将显示在详细信息中 。 属性可能属于对象的原型(而不是“自己的”属性): > x = {a:1} { a: 1 } > y = Object.create(x) > y.a 1 > y {} > Object.keys(y) [] 属...

Vue.js图表不起作用?(Vue.js chart not working?)

您正在访问created()钩子中的canvas元素,该钩子在模板附加到DOM之前调用。 要解决您的问题,您需要将代码放入组件的mounted()挂钩中。 但是,仍然无法保证模板在文档中。 所以你必须使用$ vm.nextTick()来确保DOM准备就绪。 ( 来源 )。 另外,我建议使用vue的Child组件引用 ,它比document.getElementById()更像vue(它也适用)。 Vue.component('message-graph', { template: '<c...

相关文章

更多

两种js function 声明方式

http://helephant.com/2012/07/14/javascript-function ...

error C2668: 'M' : ambiguous call to overloaded function

以下是代码: #include&lt;iostream&gt;using namespace std ...

Hadoop node 部署步骤

1.OS安装 a)RHEL 6.2 X64 i.刻录光盘安装(略) b)安装选项 i.Basic se ...

Hadoop下远程调试Child子进程

在网上想找Hadoop远程调试Child子进程的文章,但是都没有见到具体步骤是如何操作的,对于初学者来 ...

The connection to adb is down, and a severe error has occured.

启动android模拟器时.有时会报The connection to adb is down, an ...

Node.js视频教程

捷训Node.js入门教学视频,对初学者来说应该不错的,教学视频中包括javascript的基本知识的 ...

Hadoop Backup Node

要了解 Hadoop Backup Node,要从Namenode的元数据说起。 我们都知道 ...

Object Oriented Programming

Some might also contend that inheritance should be ...

Spark - A Fault-Tolerant Abstraction for In-Memory Cluster Computing

http://spark-project.org/ 项目首页 http://shark.cs.berk ...

最新问答

更多

Python / IPython奇怪的不可重现列表索引超出范围错误(Python/IPython strange non reproducible list index out of range error)

你得到IndexError的原因是你的输入文件显然不是完全用制表符分隔的。 这就是为什么当您尝试访问它时, splits[1]没有任何内容。 您的代码可以使用一些重构。 首先,你正在重复使用if -checks,这是不必要的。 这只是将cds0到7个字符,这可能不是你想要的。 我将以下内容放在一起,以演示如何重构您的代码,使其变得更加pythonic和干燥。 我无法保证它能够与您的数据集一起使用,但我希望它可以帮助您了解如何以不同的方式执行操作。 to_sort = [] # W

故事板从表格单元中延伸出来并显示其详细信息披露按钮(storyboard segue from a tablecell an its Detail Disclosure Button)

我不认为你可以链接一个特定的细节披露按钮瓦特/赛格。 我的故事板是非常程序化的B / C我使用了很多定制CGRect等。 所以我倾向于使用这样的东西: -(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"ViewControllerIdentifer"

我们可以将Gherkin功能文件与testcomplete集成(Can we integrate Gherkin feature files with testcomplete)

TestComplete不支持Gherkin功能文件。 但是,TestComplete具有SDK,因此可以自己为此创建扩展。 TestComplete does not support Gherkin feature files. However, TestComplete has SDK so it is possible to create an extension for this by yourself.

TrustAllCertificatesCallback被忽略(TrustAllCertificatesCallback is ignored)

我没有做过这样的事情,但看看我认为可以看出错误的例子。 试试这个代码: static class Program { static void Main() { var tcpclient = new TcpClient("remote.example.com", 443); var tcpstream = tcpclient.GetStream(); var sslstream = new SslStream(tcpstream,

返回嵌套元素的索引(Return index of nested element)

您需要获取父li元素的索引。 否则,您将获得列表项内锚点的索引,该索引始终为零。 $(this.parentNode).index(); You need to get the index of the parent li element. Otherwise you are getting the index of the anchor inside the list item, which will always be zero. $(this.parentNode).index();

在数组中重新编号元素的有效方法(Efficient way of re-numbering elements in an array)

您需要多次迭代列表,我认为没有办法解决这个问题。 毕竟,在开始更改元素(第二遍)之前,首先必须确定不同元素的数量(第一遍)。 但是请注意,由于对index的重复调用而not in列表中具有O(n),因此可能具有最多O(n ^ 2)的不同元素的数量。 或者,您可以使用dict而不是value_map的list 。 字典比列表具有更快的查找速度,因此,复杂性应该确实在O(n)的数量级上。 您可以使用(1)字典理解来确定旧值到新值的映射,以及(2)用于创建更新子项的列表理解。 value_map =

Express app定义的`static`文件夹无法正常工作(Express app defined `static` folder not working properly)

选项1 你可以改变这一行: app.use( express.static(__dirname + '/puplic')); //my public folder. 至 app.use('/oneTime', express.static(__dirname + '/puplic')); //my public folder 选项2 我假设你在公共文件夹中有一个js文件夹,然后你需要更改你的HTML代码:

使用node.js和socket.io每秒广播一次(Using node.js and socket.io to broadcast every second)

对于计时器值,请在服务器端本身每秒更新本地计时器。 每当有任何用户进来时,给他这个值以及计时器的总值。 然后客户端将根据dandavis评论在本地启动自己的计时器,但在服务器端保留一些间隔,如15或10秒,服务器将广播当前计时器值,以便客户端相应地进行同步。 简而言之,服务器将每隔10(n:你决定)秒后广播,但它将在本地每秒更新定时器变量。 每当客户端进入时,它将获得总计时器值和当前计时器值。 广播当前出价的休息功能可以以正常方式完成。 For timer value, keep updatin

如何让XMLSerializer将命名空间添加到嵌套对象中的属性?(How do I get the XMLSerializer to add namespaces to attributes in nested objects?)

IXmlSerializable也许? 注意我还添加了(对A ): [XmlElement("A", Namespace = "http://www.example.com/namespace")] public TestSoapHeaderTypeValuePair A {...} 代码如下: public class TestSoapHeaderTypeValuePair : IXmlSerializable { private string _type; private