2

In a vue.js component I'm trying to compile a variable in a template but its not getting compiled/converted. Any advice how I can achieve the following:

<template>
    <img src="{{ window.SETTINGS.ASSETS_DIR + 'img/foo.jpg' }}"/>
</template>

Where settings is:

window.SETTINGS = {
  ASSETS_PATH: '/wp-content/themes/my-theme/assets/',
  API_BASE_PATH: '/wp-json/wp/v2/'
}
3
  • 1
    <img v-bind:src="window.SETTINGS.ASSETS_DIR + 'img/foo.jpg'"/> use v-bind for attributes Commented Apr 13, 2018 at 10:06
  • You can use lodash templating to compile a string and do interpolation. Commented Apr 13, 2018 at 10:07
  • Your windows.SETTINGS object doesn't contain a variable called ASSETS_DIR. Commented Apr 13, 2018 at 11:55

1 Answer 1

4

It doesn't work because Vue doesn't know anything about window.SETTINGS.

You should reference window.SETTINGS to property in data object, in your Vue Component/Instance.

data() {
  return {
    settings: window.SETTINGS
  }
}

Other option could be to extend Vue.prototype If you need this over the whole app:

Vue.prototype.SETTINGS = {
  ASSETS_PATH: '/wp-content/themes/my-theme/assets/',
  API_BASE_PATH: '/wp-json/wp/v2/'
}

And then you can access It everywhere by typing:

this.SETTINGS

And last step would be to not use the interpolation, but instead go with the binding:

<img :src="SETTINGS.ASSETS_PATH + 'hello.jpg'" alt="">
Sign up to request clarification or add additional context in comments.

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.