Vue.js VueJ通过v-for与父容器通信,同时提供索引和参数
我知道我可以像这样与组件的父级通信:Vue.js VueJ通过v-for与父容器通信,同时提供索引和参数,vue.js,Vue.js,我知道我可以像这样与组件的父级通信: <container> <child-component v-for="(thing, index) in things" :key="index" v-on:thingDidSomething="thingDidSomethingInParent(index)" ></child-component> </container> <child-component v-
<container>
<child-component v-for="(thing, index) in things"
:key="index"
v-on:thingDidSomething="thingDidSomethingInParent(index)"
></child-component>
</container>
<child-component v-for="(thing, index) in things"
:key="index"
:index="index"
v-on:thingDidSomething="thingDidSomethingInParent"
></child-component>
和提供索引(键)。我可以访问子组件中的键吗?
此。$vnode.key
将为您提供子组件中的键
值。但是,$vnode
属性没有作为文件的一部分进行记录。我认为这样做最安全的方式是:
<container>
<child-component v-for="(thing, index) in things"
:key="index"
v-on:thingDidSomething="thingDidSomethingInParent(index)"
></child-component>
</container>
<child-component v-for="(thing, index) in things"
:key="index"
:index="index"
v-on:thingDidSomething="thingDidSomethingInParent"
></child-component>
以及组件
Vue.component("child-component",{
props:["index"],
methods:{
emitThingDidSomething(){
this.$emit('thingDidSomething', this.index, <other arguments>)
}
}
})
Vue.component(“子组件”{
道具:[“索引”],
方法:{
emitThingDidSomething(){
this.$emit('thingDidSomething',this.index,)
}
}
})
.您可以通过索引作为道具。谢谢您的回答!哦,这是唯一的方法吗,没有更简单的方法吗?您不能直接在子组件中访问密钥,而不将其传递给props吗?@user1506145
this.$vnode.key
子组件中的密钥将提供给您。请小心使用它,因为它是一个Vue内部值。@user1506145我更新了答案和示例,但如果需要,我仍然建议传递它。否则就看你了!:)