v-for 内的闭包,属性插值
closure within v-for, attribute interpolation
我有这个基本设置
<div v-for="n in 4">
<some-component @on-some-event="onSomeEvent(n)"></some-component>
</div>
on-some-event
已在 some-component
内派出。但我需要知道这些组件中的哪一个发送了消息。使用上面的设置,只有 n
被传递到方法中。并且事件发送的数据无处可去。
我想对函数进行插值,使方法看起来像这样
onSomeEvent(n){
return (obj)=>{
console.log(`component ${n} sent ${obj}`);
};
}
但是用 {{}}
包裹 onSomeEvent
会引发警告:attribute interpolation is not allowed in Vue.js directives and special attributes.
我可以将 n
索引传递到组件中,但这似乎不太优雅,因为我可能无法修改 some-component
我对 Vue 有点陌生,所以我可能缺少这类东西的一些核心功能?
您没有遗漏任何内容,消息是正确的,在 Vue 中,您将无法使用那样的插值。
http://vuejs.org/guide/syntax.html#Interpolations
但是,您可能想要更改管理事件和在组件之间传递数据的方式。在您的示例中,您可以像这样绑定数据:
<div v-for="n in 4">
<some-component :n="n"></some-component>
</div>
在您的组件中,声明道具:
Vue.component('some-component', {
props: ['n'],
...
现在,在每个组件中,您可以像任何其他组件一样使用 n
属性 (http://vuejs.org/guide/components.html#Props)。
然后在调度你的事件时,你可以这样调用它,不需要参数:
onSomeEvent()
在活动本身上,您可以访问 n
:
console.log('Component' + this.n + ...)
<div v-for="n in 4">
<some-component @on-some-event="onSomeEvent | pass n"></some-component>
</div>
....
filters: {
pass(handler, n) {
return function() {
handler()(n, ...arguments)
}
}
},
methods: {
onSomeEvent() {
console.log(...arguments)
}
}
我有这个基本设置
<div v-for="n in 4">
<some-component @on-some-event="onSomeEvent(n)"></some-component>
</div>
on-some-event
已在 some-component
内派出。但我需要知道这些组件中的哪一个发送了消息。使用上面的设置,只有 n
被传递到方法中。并且事件发送的数据无处可去。
我想对函数进行插值,使方法看起来像这样
onSomeEvent(n){
return (obj)=>{
console.log(`component ${n} sent ${obj}`);
};
}
但是用 {{}}
包裹 onSomeEvent
会引发警告:attribute interpolation is not allowed in Vue.js directives and special attributes.
我可以将 n
索引传递到组件中,但这似乎不太优雅,因为我可能无法修改 some-component
我对 Vue 有点陌生,所以我可能缺少这类东西的一些核心功能?
您没有遗漏任何内容,消息是正确的,在 Vue 中,您将无法使用那样的插值。 http://vuejs.org/guide/syntax.html#Interpolations
但是,您可能想要更改管理事件和在组件之间传递数据的方式。在您的示例中,您可以像这样绑定数据:
<div v-for="n in 4">
<some-component :n="n"></some-component>
</div>
在您的组件中,声明道具:
Vue.component('some-component', {
props: ['n'],
...
现在,在每个组件中,您可以像任何其他组件一样使用 n
属性 (http://vuejs.org/guide/components.html#Props)。
然后在调度你的事件时,你可以这样调用它,不需要参数:
onSomeEvent()
在活动本身上,您可以访问 n
:
console.log('Component' + this.n + ...)
<div v-for="n in 4">
<some-component @on-some-event="onSomeEvent | pass n"></some-component>
</div>
....
filters: {
pass(handler, n) {
return function() {
handler()(n, ...arguments)
}
}
},
methods: {
onSomeEvent() {
console.log(...arguments)
}
}