Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get object by string in Vue.js

I have imported some images in vue file.
I also have a string related to these images, and would like to get them dynamically using the string value.

For example:

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 `${str}Image` // I want something like this to return firstImage (image, not string)
    }
  }
}

Is there any way to turn string into object?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading