Home > Software design >  How to get object by string in Vue.js
How to get object by string in Vue.js

Time:01-20

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?

CodePudding user response:

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)
    }
  }
}

CodePudding user response:

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

  •  Tags:  
  • Related