sazr
sazr

Reputation: 25928

Execute javascript inside vue component template?

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/'
}

Upvotes: 2

Views: 3486

Answers (1)

Belmin Bedak
Belmin Bedak

Reputation: 9201

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="">

Upvotes: 4

Related Questions