2017-02-23 411 views
0

我試圖創建學習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 ?? 
    }, 
+0

你能否澄清「但我沒有運氣」?你有錯誤嗎?你看到控制檯中有任何錯誤嗎? – PatrickSteele

回答

0

這裏是更新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爲最小值。