Vuejs 单击复选框中的事件?

我在复选框上有一个 v 模型,它的值是从循环中分配的。 我希望 click 事件调用一个函数,在这个函数中我需要访问被检查的数据。触发单击时,如果我记录状态,它不会打印复选框的当前单击数据。它打印以前单击的复选框数据。是否必须在函数中传递和访问事件数据?

<div id="demo">
<ul>
<li v-for="mainCat in mainCategories">
<input
type="checkbox"
:value="mainCat.merchantId"
id="mainCat.merchantId"
v-model="checkedCategories"
@click="check(checkedCategories)"
>
{{mainCat.merchantId}}
</li>
</ul>
{{ checkedCategories }}
</div>

剧本:

var demo = new Vue({
el: '#demo',
data: {
checkedCategories: [],
mainCategories: [{
merchantId: '1'
}, {
merchantId: '2'
}] //testing with data use: [{done:false,content:'testing'}]
},
methods: {
check: function(e) {
console.log(this.checkedCategories,e)
}
}
})

小提琴: http://jsfiddle.net/bmpfs2w2/

145516 次浏览

Use @change instead of @click. Click event is triggered before value is really changed.

<input type="checkbox"
:value="mainCat.merchantId"
id="mainCat.merchantId"
v-model="checkedCategories"
@change="check($event)"
>

http://jsfiddle.net/eLzavj5f/

If you'd like the function to be called after the value has been changed, you can wrap your handler functionality inside of this.$nextTick(). You can read about $nextTick, but the gist is

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

So your handler will get called after the DOM gets updated, aka after your state has changed and the effects have been reflected in the DOM.

<input
type="checkbox"
:value="mainCat.merchantId"
id="mainCat.merchantId"
v-model="checkedCategories"
@change="check($event)"
>


// ...


check (e) {
this.$nextTick(() => {
console.log(checkedCategories, e)
})
}

Altered Grant's solution

<input
type="checkbox"
:value="mainCat.merchantId"
id="mainCat.merchantId"
v-model="checkedCategories"
@change="check($event)"
/>


// ...


check (e) {
this.$nextTick(() => {
console.log(e.target.id)
})
}

Thanks Grant