'How to create a global string in a vue (webpack) project

In my vue project I have a default image that should show up in places around the app when an image is missing or hasn't been uploaded yet. I have various class files and component calls that want to use the same image.

What is the best way to create a global variable that I can access from anywhere? I can't put it in the store because my class files (I'm using vuex-orm) are loaded before the store is declared. I would prefer not to put it in the window because I want to have a single word variable that I can call (defaultImg as opposed to window.my_project.globals.defaultImg). I could put it in .env but I want this to be checked into the repository and the same across environments so that doesn't seem right either.

What is the best way to provide a simple global string to all files in my vue project?



Solution 1:[1]

Are you using Vue 2 or 3? TL;DR best approach is to create a component.

Quick Fix

You could take the approach described in the documentation for creating plugins:

https://vuejs.org/guide/reusability/plugins.html#introduction

If you didn't want to go down the convoluted route of creating a separate plugin file just to store a single string you could probably just do something like this in your entry file where you initialize the app:

Vue 3:

app.config.globalProperties.$defaultImg = '/path/to/image.png'

Vue 2:

Vue.prototype.$defaultImg = '/path/to/image.png'

And use this in your templates like

<img :src="$defaultImage">

Best Solution

However, I think the best and the most 'Vue' way would be to create an image component which displays a given image, or the default image if src is nullish:

Vue 2 & 3

<template>
  <img :src="srcOrDefault">
<template>

Vue 3 Composition API:

<script>
const defaultImg = '/path/to/image.png'

const props = defineProps({
  src: String
});

const srcOrDefault = computed(() => {
  return props.src || defaultImg
})
</script>

Vue 2 & Vue 3 Options API:

<script>
const defaultImg = '/path/to/image.png'

export default {
  props: {
    src: String
  },
  computed: {
    srcOrDefault() {
      return this.src || defaultImg
    }
  }
}
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kissu