Vue在使用插槽时将数据发回父级

时间:2019-01-23 18:19:05

标签: vue.js

我已经在自定义组件上输入了内容,当我单击包装器组件上的下一个按钮时,我需要向父组件发送详细信息。

这在vue中怎么可能?

wrapper.vue

<template>
    <div :id="contentId" class="mt-3">    
    <div>        
        <slot></slot>        
    </div>
    <b-row class="float-right">                
                <b-col>
                    <button cssClass="e-outline" v-on:click="btnNext">{{nextButtonText}}</button>  
                </b-col> 
            </b-row>     
    </div>

    </template>

parent.vue

<template>
    <div>
        <Wrapper contentId="1">
            <CustomComponent1 />
        </wrapper>
        <Wrapper contentId="2">
            <CustomComponent1 />
        </wrapper>
    </div>
    </template>

customComponent1.vue

<template>
    <div>
        <input v-model="name" />
<input v-model="name2" />
    </div>
</template>
上面的

代码仅用于说明目的。

1 个答案:

答案 0 :(得分:2)

问题在于包装器没有天生就可以访问作用域组件的数据,因此必须手动创建这些链接。无法得知组件可能有多少个子代或插槽,因此这种功能并不是vue魔术的一部分。

因此,在示例中,您有一个父级App组件,该组件包含一个插槽中有一个Wrapper组件的MyInput

MyInput

MyInout组件不会自动更新其他组件,因此需要将其设置为$emit内部数据。

这可以通过使用watch@change侦听器进行输入来完成,也可以通过其他方式完成。您可以在变化时发出多个基准,或者对所有数据使用单个有效载荷

this.$emit("input", myData);

应用

App需要在MyInoutWrapper之间显式连接数据

<Wrapper> <MyInput @input="onInput" slot-scope="{ onInput }" /> </Wrapper>

魔术/技巧在这里发生,在这里我们使用slot-scope将输入的input发射函数绑定到onInput函数。

包装器

然后,包装器需要监听从App传递(通过Wrapper的事件)

<slot :onInput="onInput" />

其中onInput是一种可以处理数据的方法

请参见下面的示例
Edit Vue Template

我建议阅读以下内容

相关问题