Vue.js 同一组件问题的多个实例
[英] Vue.js multiple instances of same component issue
本文介绍了Vue.js 同一组件问题的多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个用于选择照片的 vue 组件.当用户单击任何照片时,照片的 id 将分配给组件内的隐藏输入字段.
现在我在同一个页面上用不同的数据使用了这个组件两次.问题是当我单击一个组件的照片时,两个组件的输入字段的值都会更新.我正在使用 vue.js 版本 2.1.10这是我的组件的简化版本.
<input type="hidden" :name="inputName" :value="currentSelectedPhoto.id"><div v-for="照片中的照片"><div v-on:click="updateSelectedPhoto(photo)"><img :src="photo.photo_url"/>
组件
出口默认{道具: {...},方法: {获取照片(){...},更新选定的照片(照片){this.currentSelectedPhoto = 照片;}}}
这就是我在 html 中使用它的方式
<div>头像照片<照片选择器照片="{{ $照片}}"输入名称=profile_photo_id"></照片选择器>
<div class="col-sm-4">封面照片<照片选择器照片="{{ $otherPhotos }}"输入名称=cover_photo_id"></照片选择器>
解决方案
基于你的 codepen示例,这是因为您在两者之间共享状态对象:
const initalState = {选定的照片:空};const PhotoSelector = Vue.extend({数据:() =>{返回初始状态},
Vue mutates 初始状态对象(通过将其包装在反应式 getter 等中),因此您需要让 data()
为实例返回一个新的状态对象以使用:
数据:() =>{返回 {选定的照片:空};},
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
};
},
这篇关于Vue.js 同一组件问题的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!