在Vue中如何从名称数组中选择随机名称?

时间:2019-03-21 11:31:48

标签: javascript vue.js

在“数据”中有一个名称数组:['Bogdan','Ruslan'...]。如何从Names数组中选择一个随机名称并将其插入<p> Names </ p>标签中?

我试图这样做-<p>{{Names[Math.floor(Math.random() * Names.length)]}}</p>,但由于某种原因,它不起作用

<f7-list
  media-list
  virtual-list
  :virtual-list-params="{ items, renderExternal, height: $theme.ios ? 63 : ($theme.md ? 73 : 46)}"
>
  <ul>
    <f7-list-item
      v-for="(item, index) in vlData.items"
      :key="index"
      media-item
      link="#"
      :title="item.title"
      :subtitle="item.subtitle"
      :style="`top: ${vlData.topPosition}px`"
    >
    <f7-block strong>
      <p>Name:{{Names[Math.floor(Math.random() * Names.length)]}}</p>
    </f7-block>
    <f7-block>
      <p>Surname:</p>
    </f7-block>
    </f7-list-item>
  </ul>
</f7-list>

<script>
export default {
    data() {
 Names: [ "Bogdan", "Vladimir", "Nikolay", "Stepan", "Sergey", "Igor", "Vladislav", "Miroslav", "Nikita", "Alexander", "Ivan", "Ruslan", "Maria", "Victoria", "Angella", "Zhanna", "Irina", "Marina", "Yulya", "Olya", "Dasha", "Natasha", "Masha"]
  const items = []
  for (let i = 1; i <= 10; i += 1) {
    items.push({
      title: `UserID ${i}`,
      // subtitle: `SurName ${i}`,
    });
  }
  return {
    items,
    vlData: {
      items: [],
    },
  };
},
methods: {
  renderExternal(vl, vlData) {
    this.vlData = vlData;
  },
  randomName(){

  },
  loadMore(event, done) {
      window.location.reload();
  }
},
}
</script>

3 个答案:

答案 0 :(得分:2)

您在数据部分做了很多事情,而是使用函数或计算值来获取您的随机名称。

例如,

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>

<div id="app">
  <p>Name:{{ randomNameFunc() }}</p>
  <p>Name:{{ randomNameProp }}</p>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        Names: ["Bogdan", "Vladimir", "Nikolay", "Stepan", "Sergey", "Igor", "Vladislav", "Miroslav", "Nikita", "Alexander", "Ivan", "Ruslan", "Maria", "Victoria", "Angella", "Zhanna", "Irina", "Marina", "Yulya", "Olya", "Dasha", "Natasha", "Masha"]
      }
    },
    computed: {
      randomNameProp: function (){
        return this.Names[Math.floor(Math.random() * this.Names.length)]
      }
    },
    methods: {
      randomNameFunc() {
        return this.Names[Math.floor(Math.random() * this.Names.length)]
      }
    }
  });
</script>

答案 1 :(得分:0)

您没有在数据对象中返回Names

尝试一下

return {
  Names,
  items,
  vlData: {
    items: [],
   },
 };

答案 2 :(得分:0)

使用computed property。例如:

return.browser.getAllWindowHandles().then((availableTabs) => {
    return browser.switchTo().window(availableTabs[availableTabs.length - 1]);
});

然后您可以使用

  data() { 
    return {
      names: ['John', 'Carlos', 'Matt'] 
    }
  },
  computed: {
    randomName() {
      let n = this.names.length
      let randomNumber = Math.floor(Math.random() * n)
      return this.names[randomNumber]
    }
  }