[Vuejs]-Vue.js select a random option from array as default

0👍

Here is the updated codepen. As you use vue.js 2.0 use the mounted method in combination with this.$tick.

Since you used v-model and added a value to the select options you have to assign the "random" value to the v-model variable.

as seen here

mounted: function() {
   this.$nextTick(function() {
      var randomVehicle = Math.floor(Math.random() * this.vehicleList.length);
      var randomLocation = Math.floor(Math.random() * this.locList.length);
      this.selectedVehicle = this.vehicleList[randomVehicle].speed;
      this.selectedLocation = this.locList[randomLocation].distance;
   });  
},

The math random calculation does nothing more then provide a range for the random selection. I just used this….length for the maximum and 0 for the minimum.

Leave a comment