App下載

Vue 中插槽是怎么發(fā)出數(shù)據(jù)的

猿友 2020-08-10 14:25:40 瀏覽數(shù) (2308)
反饋

在工作中BUG的出現(xiàn)是在所難免的,但是在寫(xiě)代碼的時(shí)候沒(méi)法實(shí)時(shí)發(fā)現(xiàn)BUG,等事后再去解決BUG,還得花很多時(shí)間去進(jìn)行log調(diào)試,這里給大家推薦一個(gè)不錯(cuò)的BUG監(jiān)控工具:Fundebug。

我們知道使用作用域插槽可以將數(shù)據(jù)傳遞到插槽中,但是如何從插槽傳回來(lái)呢?

(推薦教程:Vue 1教程

將一個(gè)方法傳遞到我們的插槽中,然后在插槽中調(diào)用該方法。無(wú)法發(fā)出事件,因?yàn)椴宀叟c父組件共享相同的上下文(或作用域)。

// Parent.vue <template> <Child> <template #default="{ clicked }"> <button @click="clicked"> Click this button </button> </template> </Child> </template>

// Child.vue <template> <div> <!-- 將“handleClick” 作為 “clicked” 傳遞到我們的 slot --> <slot :clicked="handleClick" /> </div> </template>

在本文中,我們將介紹其工作原理,以及:

  • 從插槽到父級(jí)的 emit
  • 當(dāng)一個(gè)槽與父組件共享作用域時(shí)意味著什么
  • 從插槽到祖父組件的 emit
  • 更深入地了解如何使用方法從插槽通訊回來(lái)

從插槽到父級(jí)的 emit

現(xiàn)在看一下Parent組件的內(nèi)容:

// Parent.vue <template> <Child> <button @click=""> Click this button </button> </Child> </template>

我們?cè)?Child 組件的插槽內(nèi)有一個(gè)button 。單擊該按鈕時(shí),我們要在Parent 組件內(nèi)部調(diào)用一個(gè)方法。

如果button 不在插槽中,而是直接在Parent組件的子組件中,則我們可以訪問(wèn)該組件上的方法:

// Parent.vue <template> <button @click="handleClick"> Click this button </button> </template>

當(dāng)該 button 組件位于插槽內(nèi)時(shí),也是如此:

/ Parent.vue <template> <Child> <button @click="handleClick"> Click this button </button> </Child> </template>

之所以可行,是因?yàn)樵摬宀叟c Parent 組件共享相同的作用域。

(推薦教程:Vue 2教程

插槽和模板作用域

模板作用域:模板內(nèi)部的所有內(nèi)容都可以訪問(wèn)組件上定義的所有內(nèi)容。

這包括所有元素,所有插槽和所有作用域插槽。

因此,無(wú)論該按鈕在模板中位于何處,都可以訪問(wèn)handleClick方法。

乍一看,這可能有點(diǎn)奇怪,這也是為什么插槽很難理解的原因之一。插槽最終渲染為Child 組件的子組件,但它不與Child 組件共享作用域。相反,它充當(dāng)Parent 組件的子組件。

插槽向祖父組件發(fā)送數(shù)據(jù)

如果要從插槽把數(shù)據(jù)發(fā)送到祖父組件,常規(guī)的方式是使用的$emit方法:

// Parent.vue <template> <Child> <button @click="$emit('click')"> Click this button </button> </Child> </template>

因?yàn)樵摬宀叟cParent 組件共享相同的模板作用域,所以在此處調(diào)用$emit將從Parent組件發(fā)出事件。

從插槽發(fā)回子組件

Child 組件通訊又如何呢?

我們知道如何將數(shù)據(jù)從子節(jié)點(diǎn)傳遞到槽中

// Child.vue <template> <div> <slot :data="data" /> </div> </template>

以及如何在作用域內(nèi)的插槽中使用它:

// Parent.vue <template> <Child> <template #default="{ data }"> {{ data }} </template> </Child> </template>

除了傳遞數(shù)據(jù),我們還可以將方法傳遞到作用域插槽中。如果我們以正確的方式連接這些方法,則可以使用它來(lái)與Child組件通信:

// Parent.vue <template> <Child> <template #default="{ clicked }"> <button @click="clicked"> Click this button </button> </template> </Child> </template>

// Child.vue
<template>
  <div>
    <!-- Pass `handleClick` as `clicked` into our slot -->
    <slot :clicked="handleClick" />
  </div>
</template>

每當(dāng)單擊按鈕時(shí),就會(huì)調(diào)用Child組件中的handleClick方法。

(推薦微課:Vue 2.x 微課

以上就是關(guān)于在Vue中插槽是怎么發(fā)送數(shù)據(jù)的詳細(xì)內(nèi)容了,希望對(duì)大家有所幫助。

原文:stackoverflow.com/questions/50942544/emit-event-from-content-in-slot-to-parent/50943093

0 人點(diǎn)贊