Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!