0
votes

I'm having some issues to make an avatar picker works...

After click to select the avatar in not being replaced and with the error TypeError: Cannot read property 'src' of undefined at VueComponent.selectAvatar

I'm currently using Vuetify and the v-avatar component with a v-for to load all the images.

Any idea how to make it work?

HTML

<v-flex xs12 pt-0 pb-0>
  <h1 class="title mb-4">User Details</h1>
  <v-avatar
    size="100px"
  >
    <img
      :src="this.selectedAvatar"
      alt="Avatar"
    >
  </v-avatar>
</v-flex>
<v-flex x12>
  <v-btn
    color="primary"
    flat="flat"
    small
    @click="selectAvatarDialog = true"
    class="avatar-btn"
  >
    Update avatar
  </v-btn>
</v-flex>

<v-dialog
  v-model="selectAvatarDialog"
  max-width="80%"
>
  <v-card>
    <v-container fluid pa-2>
        <v-layout row wrap align-center justify-center fill-height>
          <v-flex xs6 sm4 md3 lg2 my-2 class="text-xs-center"
          v-for="(avatar,i) in avatars"
          :key="i">
            <v-img
              :src="avatar.src"
              aspect-ratio="1"
              width="100px"
              max-width="100px"
              min-width="100px"
              class="dialog-avatar-img"
              @click="selectAvatar()"
            ></v-img>
          </v-flex>
        </v-layout>
      <v-card-actions class="mt-2">
        <v-spacer></v-spacer>

        <v-btn
          color="primary"
          flat="flat"
          @click="selectAvatarDialog = false"
        >
          Cancel
        </v-btn>
      </v-card-actions>
    </v-container>
  </v-card>
</v-dialog>

JS

export default {
  layout: 'default',

  data() {
    return {
      selectAvatarDialog: false,
      avatars: [
        {src: require('@/assets/images/avatar-01.png') },
        { src: require('@/assets/images/avatar-02.png') },
        { src: require('@/assets/images/avatar-03.png') },
        { src: require('@/assets/images/avatar-04.png') },
        { src: require('@/assets/images/avatar-05.png') }
      ],
      selectedAvatar: require('@/assets/images/avatar-01.png'),
    }
  },
  methods: {
    selectAvatar(){
      this.selectedAvatar = this.avatar.src
      console.log('Avatar selected')
    }
  }
}

Thank you

1

1 Answers

1
votes

The problem is in your selectAvatar method where you are trying to use 'this.avatar' but it doesn't exist. The avatar in your for loop isn't passed to your script. You should do like this:

<v-img
  ...
  @click="selectAvatar(i)"
></v-img>

And in your script:

methods: {
    selectAvatar(i){
      this.selectedAvatar = this.avatars[i].src
      console.log('Avatar selected')
    }
  }