[Vuejs]-How to get object by string in Vue.js

4👍

Since firstImage is in the data object you can just selecting it by this with name in [ ]

import firstImage from '../images/first_image.png'
import secondImage from '../images/second_image.png'

export default {
  data() {
    return {
      firstImage,
      secondImage
    }
  },
  computed: {
    myImage() {
      let str = 'first'; // this string value varies.
      return this[`${str}Image`] // I want something like this to return firstImage (image, not string)
    }
  }
}

0👍

Based on the answer of @S.Visser which is correct, but It seems that you want something dynamic (str should be dynamic) because the current logic returns always the firstImage, to solve this you’ve to define str as parameter for a function return from the computed property :

 computed: {
    myImage() {
     return (str)=>this[`${str}Image`] 
    }
  }

then you could use the property like this.myImage('first') or myImage('first') in template

Leave a comment