8

I have created a vue component for selecting photos. When the user clicks any photo the id of the photo will be assigned to a hidden input field inside the component.

Now I have used this component twice on the same page with different data. The problem is when I click on the photo of one component the value of the input field of both the components gets updated. I am using vue.js version 2.1.10 Here is the simplified version of my component.

<div>
    <input type="hidden" :name="inputName" :value="currentSelectedPhoto.id">
    <div v-for="photo in photos">
        <div v-on:click="updateSelectedPhoto(photo)">
            <img :src="photo.photo_url" />
        </div>
    </div>
</div>

The Component

export default {
    props: {
        ...
    },
    methods: {
        getPhotos(){
            ...
        },
        updateSelectedPhoto(photo){
            this.currentSelectedPhoto = photo;
        }
    }
}

This is how I am using it in html

<div>
    <div>
        Profile Photo
        <photo-selector
            photos="{{ $photos }}"
            input-name="profile_photo_id"
            >
        </photo-selector>
    </div>
    <div class="col-sm-4">
        Cover Photo
        <photo-selector
            photos="{{ $otherPhotos }}"
            input-name="cover_photo_id"
            >
        </photo-selector>
    </div>
</div>
2

1 Answer 1

9

Based on your codepen sample, it's because you are sharing the state object between the two:

const initalState = {
  selectedPhoto: null
};

const PhotoSelector = Vue.extend({
  data: () => {
    return initalState
  },

Vue mutates the initial state object (by wrapping it in reactive getters etc), so you need to have data() return a fresh state object for the instance to use:

data: () => {
  return {
    selectedPhoto: null
  };
},
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.