2017-04-06 61 views
0

我有在父組件中生成的事件,並且孩子必須對它作出反應。我知道這不是vuejs2的推薦方法,我必須做一個$root發射,這是非常糟糕的。所以我的代碼是這樣的。來自父母組件的事件

<template> 
    <search></search> 
    <table class="table table-condensed table-hover table-striped" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10"> 
     <tbody id="trans-table"> 
      <tr v-for="transaction in transactions" v-model="transactions"> 
       <td v-for="item in transaction" v-html="item"></td> 
      </tr> 
     </tbody> 
    </table> 
</template> 

<script> 
    import Search from './Search.vue'; 

    export default { 
     components: { 
      Search 
     }, 
     data() { 
      return { 
       transactions: [], 
       currentPosition: 0 
      } 
     }, 
     methods: { 
      loadMore() { 
       this.$root.$emit('loadMore', { 
        currentPosition: this.currentPosition 
       }); 
      } 
     } 
    } 
</script> 

,你可以看到loadMore被觸發無限滾動和事件被髮送到子組件的搜索。那麼不只是搜索,而是因爲它的根源,它正在向每個人播放。

這是什麼更好的方法。我知道我應該使用道具,但我不確定在這種情況下我該怎麼做。

+1

節你可以使用這個命令直接在孩子身上發射:$ children [index]。$ emit:https://vuejs.org/v2/api/#vm-children – Potray

+0

Search組件是孩子嗎?一個道具? –

+0

@RoyJ是搜索是一個孩子,你可以在這裏看到的代碼我在行號2提供模板,我可以添加一個道具,但這是我的問題我如何使用道具來發出loadMore? – madeye

回答

5

只需要一個變量(稱爲moreLoaded),您每次調用loadMore時都會調用該變量。作爲道具傳遞給您的search組件。在搜索中,您可以watch moreLoaded並採取相應措施。

更新
哈克? 我的解決方案?嗯,我從來沒有! ;)

您也可以使用localized event bus。其設置是這樣的:

export default { 
    components: { 
     Search 
    }, 
    data() { 
     return { 
      bus: new Vue(), 
      transactions: [], 
      currentPosition: 0 
     } 
    }, 
    methods: { 
     loadMore() { 
      this.bus.$emit('loadMore', { 
       currentPosition: this.currentPosition 
      }); 
     } 
    } 
} 

,並通過它來搜索:

<search :bus="bus"></search> 

這將需要bus爲道具(當然),並有像

created() { 
    this.bus.$on('loadMore', (args) => { 
     // do something with args.currentPosition 
    }); 
} 
+0

這肯定會工作,但它感覺有點哈克。 – madeye

+0

查看更新的答案。 –

+0

第二種解決方案是一個很好的解決方案。 :)謝謝 – madeye