简体   繁体   English

Vue.js相同组件问题的多个实例

[英]Vue.js multiple instances of same component issue

I have created a vue component for selecting photos. 我已经创建了一个用于选择照片的vue组件。 When the user clicks any photo the id of the photo will be assigned to a hidden input field inside the component. 当用户单击任何照片时,照片的ID将被分配给组件内的隐藏输入字段。

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. 我正在使用vue.js版本2.1.10这是我的组件的简化版本。

<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 这就是我在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: 基于您的codepen示例,这是因为您在两者之间共享状态对象:

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: Vue会改变初始状态对象(通过将其包装在反应性getter等中),因此您需要让data()返回一个新的状态对象供实例使用:

data: () => {
  return {
    selectedPhoto: null
  };
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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