[Vuejs]-I am trying to render a random array element from a button click using axios and a local json file. What am I missing?

0👍

Add a computed property called randomQuote as follows :

<script>
import axios from 'axios'

export default {
  name: 'Teacup',
  data() {
    return {
      teacupDataList: []
    }
  },
 computed:{
  randomQuote(){
  const rand=Math.floor(Math.random() * this.teacupDataList.length)
     return this.teacupDataList[rand]?this.teacupDataList[rand].quote:""
   }
  },
  methods: {
    getTeacupData() {
      axios.get('/teacupProph.json').then((response) => {
        this.teacupDataList = response.data
      })
    }
  }
}
</script>

in template don’t use v-for loop just call the computed property :

<template>
  <div>
    <button v-on:click="getTeacupData">Get Teacup Data</button>
    <!-- <div>{{ teacupDataList }}</div> -->

      <div>
        <span class="quote">
          {{
            randomQuote
          }}</span>
      </div>

  </div>
</template>

Edit

place your json file inside the components folder and call it like axios('./teacupProph.json') and fix the @:click to @click, check this code

Leave a comment