VueJS通过v-for与父容器通信,提供索引和参数

use*_*145 2 vue.js

我知道我可以与这样的组件的父进行通信:

<container>
    <child-component v-for="(thing, index) in things"
    :key="index"
    v-on:thingDidSomething="thingDidSomethingInParent(index)"  
    ></child-component>
</container>
Run Code Online (Sandbox Code Playgroud)

但是,如果我想从thingDidSomething子方法中提供参数,该怎么办:

v-on:thingDidSomething="thingDidSomethingInParent" 
Run Code Online (Sandbox Code Playgroud)

提供索引(键).我可以访问子组件中的密钥吗?

Ber*_*ert 6

this.$vnode.key将为您提供key子组件内的值.但该$vnode属性未记录为公共API的一部分.我认为最安全的方法是这样的:

<child-component v-for="(thing, index) in things"
:key="index"
:index="index"
v-on:thingDidSomething="thingDidSomethingInParent"  
></child-component>
Run Code Online (Sandbox Code Playgroud)

和组件

Vue.component("child-component",{
    props:["index"],
    methods:{
        emitThingDidSomething(){
            this.$emit('thingDidSomething', this.index, <other arguments>)
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

例子.