0

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?

2 Answers 2

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)
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

you beat me to it! I also think op could simply name the properties of 'this' i.e. "firstImage": firstImage
@JTInfinite This is what return { firstImage, secondImage } does. It's short syntax for firstImage: firstImage.
yeah you're right of course
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.