David J. David J. - 17 days ago 5
Javascript Question

Getting select options from computed properties with Vue JS

I am trying to get a select from to work with Vue using a computed property.

Here's a fiddle I'm working with: https://jsfiddle.net/2m18ab1v/13/

Here's what my view-model looks like:

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;
}
}

});


And the 'protocol' object referenced in the data:

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


I would like to have as my
<select>
choices "bit/s" and "kilometers". I've been trying something like this in my template:

<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)
returns
Object { bandwidth: Getter, distance: Getter, 1 more… }


So apparently, what I am trying to get is an object of some sort. I'm somewhat new to Vue and I'm trying to make sense of how the "Getter" works. Is there a straightforward way to get its value?

Answer

When you are trying to collect the units, using += in js won't get you the desired result. In this working fiddle, I used concat instead, to concat the units under wireless with others. (assuming you have other protocol categories on the same data tree level as wireless) Depending on your actual need, you may need push. Take a look at their docs:
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

Comments