Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 798
Sajjad Ashraf Avatar asked May 07 '17 15:05

Sajjad Ashraf


People also ask

Can you have multiple Vue instances?

Working with multiple Vue instancesIt is totally legal and fine to have multiple Vue instances on your page controlling different parts and pieces of it. In fact, you can even have your instances communicate with each other by storing them in variables within the global namespace.

Does Vue reuse components?

Vue components, on the other hand, are great when you want to reuse template code, aka child component, that can be used in multiple parent components.

Is Vue class component deprecated?

Due to vue-class-component is deprecated in vue3. There is a alternative one in vue3.

How do you reset a Vue component?

To reset a component's initial data in Vue. js, we can create a function that returns the initial data. Then we can call the function to reset the data. to create the initialState function that returns an object with the initial data.


1 Answers

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
  };
},
like image 199
Matt Avatar answered Sep 18 '22 20:09

Matt