简体   繁体   English

带空格的Javascript对象键

[英]Javascript object keys with spaces

I'm playing around with the vue.js library, and I'm trying to make a change to the grid component example located here: http://vuejs.org/examples/grid-component.html 我正在玩vue.js库,我正在尝试更改位于此处的网格组件示例: http//vuejs.org/examples/grid-component.html

The sorting breaks when I add a space to one of the column names. 当我向其中一个列名称添加空格时,排序会中断。 See here: http://jsfiddle.net/greene48/9d1f0858/ 见这里: http//jsfiddle.net/greene48/9d1f0858/

The column name gets passed through the sortBy function, which updates the sortKey variable to be the column name, and toggles the appropriate sortOrders key to be either -1 or 1. 列名称通过sortBy函数传递,该函数将sortKey变量更新为列名称,并将相应的sortOrders键切换为-1或1。

sortBy: function (key) {
      this.sortKey = key
      this.sortOrders[key] = this.sortOrders[key] * -1
    }

Does anyone know why this doesn't work? 有谁知道为什么这不起作用? When I check the value of sortKey and sortOrders[key] they seem to be updating correctly. 当我检查sortKey和sortOrders [key]的值时,它们似乎正在正确更新。 I think it must have something to do with not being able to use a space in the built in Vue.js orderBy filter. 我认为它必须与内置的Vue.js orderBy过滤器中无法使用空间有关。 So it must break here: 所以必须打破这里:

<tr v-for="entry in data | filterBy filterKey | orderBy sortKey sortOrders[sortKey]">
        <td v-for="key in columns">
          {{entry[key]}}
        </td>
</tr>

But I don't see anything in the Vue.js docs on how to fix this. 但我没有在Vue.js文档中看到有关如何解决这个问题的任何内容。 Anyone have any ideas? 有人有主意吗?

One easy fix would be to replace key power value with power_value and then change the header manually after the Vue rendering using pure javascript like this 一个简单的解决方法是用power_value替换关键power value ,然后使用像这样的纯javascript在Vue渲染后手动更改标题

document.querySelectorAll('#demo thead th')[1].textContent = 'Power value';

Here is working jsfiddle 这是工作jsfiddle

I would suggest not making your property names dependent on the way you want them presented in your front end. 我建议不要让你的属性名称取决于你希望它们在你的前端呈现的方式。

Use names that do not cause these issues as I suggested in my comment. 如我在评论中所建议的那样,使用不会导致这些问题的名称。

Your thought of mapping these names to an output value sounds reasonable. 您将这些名称映射到输出值的想法听起来很合理。

You could even go as far as looking into the approaches described in this thread . 你甚至可以去研究这个线程中描述的方法。 Though that already creates constraints again. 虽然这已经再次造成了限制。

You should surround the sortKey with square brackets, 你应该用方括号括sortKey

orderBy [sortKey] sortOrders[sortKey]

http://jsfiddle.net/9d1f0858/2/ http://jsfiddle.net/9d1f0858/2/

However, I agree to the above said to avoid to use property names with whitespaces. 但是,我同意上述说法,以避免使用带有空格的属性名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM