Vue 选择影响其他选择器当前选择的选择



我有一个显示某个Nova资源的表。对于每一行,我都有一个选择器,允许我从下拉菜单中执行一个操作。问题是,假设有3行。每一行都有相同的选择器。假设选择器有选项A, B和c。如果我转到第一行并选择选项B,其他选择器也将其当前选择的值更改为B。我假设这是因为所有选择器都具有相同的v-model绑定,但我不确定如何解决这个问题。

表和选择器的代码:

<table id="favorites">
<tr>
<th>ID</th>
<th>Title</th>
<th>Source</th>
<th>Description</th>
<th>Date of Creation</th>
<th>Posted Status</th>
<th>Actions</th>
</tr>

<tr v-for="(favorite, index) in favorites" :key="index">
<td>{{favorite.id}}</td>
<td>{{favorite.title}}</td>
<td>{{favorite.source}}</td>
<td>{{favorite.description}}</td>
<td>{{favorite.created_at}}</td>
<td>
<div v-if="favorite.posted_status === 2">
<button class="button-posted button4">Posted</button>
</div>
<div v-else>
<button class="button-not-posted button4">Not Posted</button>
</div>
</td>
<td>
<select @change="toggle_posted(favorite)" v-model="selected_state" class="form-control form-control-lg">
<option selected disabled>Choose an action </option>    
<option v-for="(state, index) in posted_states" :key="index" :value="state.id">{{state.name}}</option>
</select>
</td>
</tr>
</table>

我想分开选择器,这样它们就不会相互镜像。同样值得注意的是,当其他选择器改变时,它们实际上并不调用toggle_posted方法。只有我选择的选择器。

修复此问题的直接方法是为favorites中的每个列表项添加selected_state属性:

new Vue({
el:"#app",
data: () => ({
favorites: [
{ id:1, title:'1', source:'1', description:'1', created_at:'1', posted_status: 1, selected_state:null },
{ id:2, title:'2', source:'2', description:'2', created_at:'2', posted_status: 2, selected_state:null }
],
selected_state: null,
posted_states: [
{ id:1, name:'1' }, { id:2, name:'2' }
]
}),
methods: {
toggle_posted(favorite) {
console.log(favorite)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<table id="favorites">
<tr>
<th>ID</th>
<th>Title</th>
<th>Source</th>
<th>Description</th>
<th>Date of Creation</th>
<th>Posted Status</th>
<th>Actions</th>
</tr>
<tr v-for="(favorite, index) in favorites" :key="index">
<td>{{favorite.id}}</td>
<td>{{favorite.title}}</td>
<td>{{favorite.source}}</td>
<td>{{favorite.description}}</td>
<td>{{favorite.created_at}}</td>
<td>
<div v-if="favorite.posted_status === 2">
<button class="button-posted button4">Posted</button>
</div>
<div v-else>
<button class="button-not-posted button4">Not Posted</button>
</div>
</td>
<td>
<select @change="toggle_posted(favorite)" v-model="favorite.selected_state" class="form-control form-control-lg">
<option selected disabled>Choose an action </option>    
<option v-for="(state, index) in posted_states" :key="index" :value="state.id">{{state.name}}</option>
</select>
</td>
</tr>
</table>
</div>

最新更新