vue.js从数组中选择一个随机选项为默认
问题描述:
我试图创建学习vue.js一个小工具,它应该回到它需要去的地方的时候:Codepenvue.js从数组中选择一个随机选项为默认
它适用于现在,但或多或少我想在页面加载时从每个数组中添加一个随机值。我将如何做到这一点?
<select class="selectpicker" id="locationApp" v-model="selectedLocation">
<option v-for="entry in locList" v-bind:value="entry.distance">{{ entry.name }}</option>
</select>
-
var App = new Vue({
el: '#App',
data: {
locList: [
{ name: 'New York', distance: '100' },
{ name: 'Barcelona', distance: '500' },
{ name: 'Hawaii', distance: '600' }
],
vehicleList: [
{ name: 'Car', speed: '100' },
{ name: 'Bicycle', speed: '25' },
{ name: 'A pair of Shoes', speed: '5' }
],
selectedVehicle: '0', // here I'd like to add a random speed
selectedLocation: '0',// here I'd like to add a random distance
},
computed: {
calculateThis: function() {
return Math.abs(this.selectedLocation/this.selectedVehicle)
}
}
});
我读到就绪标签:
ready: function() {
//I guess I have to grab the select here somehow ??
},
答
这里是更新codepen。在使用vue.js 2.0时,请使用mounted方法和this.$tick。
由于您使用了v-模型并为选择选项添加了一个值,因此必须将“随机”值分配给v-模型变量。
这里看到
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;
});
},
数学随机运算方法确实没有更多然后提供随机选择一个范围。我只用这个......长度为最大值,0为最小值。
你能否澄清“但我没有运气”?你有错误吗?你看到控制台中有任何错误吗? – PatrickSteele