Vue2中如何从v-for渲染的子组件向父组件传值与索引
Vue2 动态渲染子组件传递值与索引的解决方法
在Vue2中处理v-for循环渲染的子组件向父组件传值并附带索引时,你之前的写法无效是因为直接写setTitle(value, index)时,value并非子组件抛出的参数,而是父组件作用域内的变量(通常是undefined)。以下两种可行方案:
方案一:父组件通过$event接收子组件值,同时传入索引
父组件模板中,利用$event捕获子组件emit的参数,再拼接v-for的索引:
<child-component v-for="(item, index) in yourList" :key="index" @title-change="setTitle($event, index)" ></child-component>
子组件中只需抛出值即可:
// 子组件内触发事件 this.$emit('title-change', newTitleValue)
父组件的方法正常接收两个参数:
methods: { setTitle(value, index) { // 这里可以拿到子组件传递的value和对应的索引index console.log('标题值:', value, '组件索引:', index) } }
方案二:子组件接收索引后,与值一起抛出
先将v-for的索引通过props传递给子组件:
<!-- 父组件模板 --> <child-component v-for="(item, index) in yourList" :key="index" :component-index="index" @title-change="setTitle" ></child-component>
子组件定义props接收索引:
// 子组件脚本 export default { props: { componentIndex: { type: Number, required: true } }, methods: { handleTitleChange() { // 同时抛出值和索引 this.$emit('title-change', newTitleValue, this.componentIndex) } } }
父组件方法直接接收两个参数:
methods: { setTitle(value, index) { // 处理逻辑 } }
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

