[Vuejs]-How do I generate array values in Vue.js and show them?

2๐Ÿ‘

โœ…

Here is a dynamic array value display :

<template>
  <div>
    <h2 v-for="player in players" v-bind:key="player.prop2">{{ player.prop1 }}</h2>
  </div>
</template>

<script>
export default {
  name: "FrontPage",
  data: function() {
    return {
      players: [{ prop1:this.ngen(), prop2:0}, 
                { prop1:this.ngen(), prop2:1},
                { prop1:this.ngen(), prop2:2}]
    };
  },
  methods: {
    ngen: function() {
      return Math.random();
    }
  }
};
</script>

1๐Ÿ‘

Basing on what you want to get as results, I think itโ€™s not necessary to have the player array in your data object.

Just define your random method and call it in your template.

<template>
    <div>
        <h2> {{ ngen() }} </h2>
        <h2> {{ ngen() }} </h2>
        <h2> {{ ngen() }} </h2>
    </div>
</template>

or just do a call of the JavaScript random function directly

1๐Ÿ‘

first you should call ngen with this.ngen()

also your players are in array

<template>
  <div>
    <h2>{{ player[0].ap }}</h2>
    <h2>{{ player[1].df }}</h2>
    <h2>{{ player[2].iq }}</h2>
  </div>
</template>

see live example

https://codesandbox.io/s/elated-sunset-yphur

1๐Ÿ‘

Change your code like this:

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: {
                'ap': this.ngen(),
                'df': this.ngen(),
                'iq': this.ngen(),
            }
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}

<template>
    <div>
        <h2> {{ player.ap }} </h2>
        <h2> {{ player.df }} </h2>
        <h2> {{ player.iq }} </h2>
    </div>
</template>

Leave a comment