Search code examples
vue.jswebpackvuex

Trouble using uploaded photo stored in vuex in vue component


I am able to upload a photo to be used as an avatar, but can only get my default photo to display. When I try to access the newly uploaded file, the component shows $store.state.photo. I believe I may need to require the photo because of something to do with webpack but I don't understand where I should do that. I was able to do that in my vuex store, but not within the component.

When I check the vue dev tools, the photo that has just been uploaded does appear as the new value for state.photo, it just won't display.

Vue Component

<v-avatar size="70" class="mb-2">
   <img :src="$store.state.photo" alt="$store.state.name" />
</v-avatar>

Vuex Store

state: {
    photo: require('../../backend/public/users/default.jpg')
  },

I tried the following in the data of the component but it doesn't work. What am I missing?

data() {
    return {    
      photo: require(`../backend/public/users/${this.$store.state.photo}`)
    };
  },

Solution

  • Displaying a default picture when the users have not uploaded theirs is a presentation concern, not an logical state concern; you should not be using Vuex for that. You can initialize the state/data with photo: null instead, which better models that a photo does not currently exist.

    Furthermore, for this sort of static assets it's a bad idea to use relative paths, which will break if you ever move the component to another folder. Relatively newer vue-cli projects are configured to use @ as the src folder.

    So your component could look like

    <v-avatar size="70" class="mb-2">
       <img :src="$store.state.photo || '@/backend/public/users/default.jpg'" alt="$store.state.name" />
    </v-avatar>
    

    And as long as you're actually initializing empty values as null instead of something like '', it should do what you want