Vue Js. How can I handle v-for data as number?

Viewed 61

Hello I am new coding at vue.js, sorry if I can't explain myself as clearly. I have problem with v-for:

<img :src="i.images.480w_still.url" />

I'm using Giphy api to search gifs and I get a response of so many images. I want to use the resized as 480w version and list them all, but when I get this response data.data, I can't use the 480w_still object:

.then((res) => {
   this.list = res.data.data;
   console.log(this.list);})` 

The console representation of the object:

pushing to list array and showing console.log

2 Answers

In JavaScript, variable names can't begin with a number. Object properties can, but in that case you can't use dot notation to access them. So that means you'll have to use bracket notation to access this property 480w_still:

<img :src="i.images['480w_still'].url" />

Bracket notation allows you to access property names that wouldn't be valid variable names.

Hi redrodawn probably you are facing problems trying to get this property 480w_still because the only way you can get a property with especial characters is using this syntax : i.images['480w_still'].url although i recommend you to use maps instead. this is an example i've just made using giphy's api you just need to add your own api key

const app = new Vue({
  el: '#app',
  data: {
    categories: []
  },
  mounted() {
    this.getGiphyTrends()
  },
  methods: {
    getGiphyTrends() {
       axios.get('https://api.giphy.com/v1/gifs/categories?api_key=YOUR_API_KEY&limit=5').then(({data}) => {
      this.categories = data.data.map(category => ({name: category.name, images: category.gif.images['480w_still']}))  
       } );
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="category in categories" >
    <h2>{{category.name}}</h2>
    <img v-for="(image, index) in category.images" :key="index" :src="image" />
  </div>
</div>

Related