【问题标题】:vue.js select a random option from array as defaultvue.js 从数组中选择一个随机选项作为默认值
【发布时间】:2017-02-23 18:16:46
【问题描述】:

我尝试创建一个学习 vue.js 的小工具,它应该返回到某个地方所需的时间:Codepen

它现在或多或少地工作,但我想在页面加载时从每个数组中添加一个随机值。我该怎么做?

<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 ??
   },

【问题讨论】:

  • 你能澄清一下“但我没有运气”吗?你收到错误了吗?您在控制台中看到任何错误吗?

标签: arrays random vue.js


【解决方案1】:

这是更新后的codepen。在使用 vue.js 2.0 时,请结合使用 mounted 方法和 this.$tick

由于您使用了 v-model 并向选择选项添加了一个值,因此您必须将“随机”值分配给 v-model 变量。

在这里看到

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为最小值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 2017-07-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2016-04-14
    • 1970-01-01
    相关资源
    最近更新 更多