gpt4 book ai didi

vue.js - Vuejs的v-for中如何处理组件发出的事件

转载 作者:搜寻专家 更新时间:2023-10-30 22:20:33 25 4
gpt4 key购买 nike

我正在尝试处理由 v-for 呈现的组件发出的事件。
例如,我制作了一个 combobox 组件,它在更改值时发出事件。
它通过 this.$emit('item_change', item); 发出事件。
我想为对应的用户处理这个事件。
在下面的代码中,我想在更改 usercombobox 的值时更改用户的 status 值。
当使用 v-on:item_change="status_change"
时,它获取 item 作为参数 example
但是它没有将 item 作为 v-on:item_change="status_change(item , user)" 中的参数,尽管 combobox 发出了带有item 的事件,userstatus 保持原始值。

我该如何解决这个问题?

JSFiddle Example

<div id="mainapp">
<table>
<thead>
<th>Name</th><th>Status</th>
</thead>
<tbody>
<tr v-for="user in users">
<td>{{user.name}}</td>
<td><combobox v-bind:default="user.status" v-bind:data="status_codes" v-on:item_change="status_change(item, user)"></combobox></td>
</tr>
</tbody>
</table>
</div>

JS代码

var combobox = Vue.component('combobox', {
data: function () {
return {
selected_item:{title:'Select', value:-1},
visible:false
}
},
props:['data','default','symbol'],
template: `
<div class="combobox">
<span class="symbol" v-if="!symbol">
<i class="fa fa-chevron-down" aria-hidden="true" ></i>
</span>
<span class="main" v-on:click="toggleVisible">{{selected_item.title}}</span>
<ul class="combodata" v-if="visible">
<li class="item" v-for="item in data" v-on:click="select(item)">{{item.title}}</li>
</ul>
</div>
`,
created:function(){
if(this.data.length>0){
if(this.default == null || this.default == undefined || this.default =='') this.default=0;
this.selected_item = this.data[this.default];
}
},
methods:{
toggleVisible:function(){
this.visible = !this.visible;
},
select:function(item){
if(this.selected_item != item){
this.selected_item= item;
this.$emit('item_change', item);
}
this.visible = false;
}
}
});

var app=new Vue({
el:"#mainapp",
data:{
status_codes:[{title:'Inactive', value:0},{title:'Active', value:1}],
users:[{name:'Andrew', status:1},{name:'Jackson', status:0},{name:'Tom', status:1}]
},
methods:{
status_change:function(item,user){ //This gets only the parameter from the event. How could I pass the additional parameters to this function?
console.log(item,user);
try{
user.status = item.value;
}catch(e){ console.log}
}
}
});

最佳答案

您需要将 $event 传递给您的 status_change 处理程序而不是 item

<div id="mainapp">
<table>
<thead>
<th>Name</th>
<th>Status</th>
</thead>
<tbody>
<tr v-for="user in users">
<td>{{user.name}}</td>
<td>
<combobox v-bind:default="user.status" v-bind:data="status_codes" v-on:item_change="status_change($event, user)"></combobox>
</td>
</tr>
</tbody>
</table>
</div>

JSFiddle

See the Vue docs here about event handling:Sometimes we also need to access the original DOM event in an inline statement handler. You can pass it into a method using the special $event variable

关于vue.js - Vuejs的v-for中如何处理组件发出的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52387523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com