简体   繁体   中英

Vue.js multiple instances of same component issue

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>

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
  };
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM