【发布时间】:2018-09-18 23:19:15
【问题描述】:
我正在尝试处理由v-for 呈现的组件发出的事件。
例如,
我制作了一个combobox 组件,它在更改值时会发出事件。
它通过this.$emit('item_change', item); 发出事件。
我想为对应的用户处理这个事件。
在下面的代码中,我想在更改user的combobox的值时更改用户的status值。
当使用v-on:item_change="status_change"
example
时,它得到item作为参数
但是它没有将item 作为v-on:item_change="status_change(item , user)" 中的参数,尽管combobox 使用item 发出事件,并且user 的status 保持原始值。
我该如何解决这个问题?
<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}
}
}
});
【问题讨论】:
-
如何将
user的index传递给组件? -
@talent_developer 没有其他解决方案吗?然后它不能在全球范围内使用。我想是的。
-
找出解决方案。
标签: vue.js vuejs2 vue-component