【问题标题】:Getting select options from computed properties with Vue JS使用 Vue JS 从计算属性中获取选择选项
【发布时间】:2017-03-14 17:06:29
【问题描述】:

我正在尝试使用计算属性从 Vue 中获得选择。

这是我正在使用的小提琴:https://jsfiddle.net/2m18ab1v/13/

这是我的视图模型的样子:

var vm = new Vue({
        el: "#app-container",
        data: {
            offer: {
                unit: '',
                tags: '',
            },
            protocol: protocol
        },             
        computed: {
            getUnits: function(){
                var unitsList = [];
                var tagList = this.offer.tags.split(",");
                console.log(tagList);
                for (var i=0; i<tagList.length; i++){
                    unitsList += this.protocol[tagList[i]]["units"];
                }
                console.log(unitsList);
                return unitsList;
            }
        }

    });

以及数据中引用的'protocol'对象:

var protocol = {"wireless":
                {
                 "units": {"bandwidth": "bit/s", "distance": "kilometers"},
                 "children": [],
                }

我希望&lt;select&gt; 选择“比特/秒”和“公里”。我一直在我的模板中尝试这样的事情:

           <div id="app-container">
                  <select v-model="offer.unit">
                    <option  v-for="item in getUnits" v-bind:value="value">
                      {{ item }}

                    </option>
                  </select>
              </div>

console.log(unitsList) 返回Object { bandwidth: Getter, distance: Getter, 1 more… }

显然,我想要得到的是某种对象。我对 Vue 有点陌生,我试图理解“Getter”是如何工作的。有没有直接的方法来获得它的价值?

【问题讨论】:

    标签: javascript vue.js reactive


    【解决方案1】:

    当您尝试收集单位时,在 js 中使用 += 不会得到您想要的结果。在这个working fiddle 中,我改用concat,将wireless 下的units 与其他人连接。 (假设您在与wireless 相同的数据树级别上有其他协议类别)根据您的实际需要,您可能需要push。看看他们的文档:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

    【讨论】:

      猜你喜欢
      • 2016-04-18
      • 2019-12-06
      • 2013-10-09
      • 2020-04-25
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      相关资源
      最近更新 更多