2017-02-17 94 views
2

我遵循這個教程:https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication如何解決未捕獲的ReferenceError:總線沒有定義? (vue.js 2)

它從一個部件將數據傳遞到其他部件

見下面我的情況。我試着像

我的看法是這樣的:

<div class="row"> 
    <div class="col-md-3"> 
     <search-filter-view ...></search-filter-view> 
    </div> 
    <div class="col-md-9"> 
     <search-result-view ...></search-result-view> 
    </div> 
</div> 

我的搜索過濾器視圖組件是這樣的:

<script> 
    export default{ 
     props:[...], 
     data(){ 
      return{ 
       ... 
      } 
     }, 
     methods:{ 
      filterBySort: function (sort){ 
       bus.$emit('sort-param', sort) 
       this.sort = sort 
       ... 
      } 
     } 
    } 
</script> 

我的搜索結果視圖組件是這樣的:

<script> 
    export default { 
     props:[...], 
     data() { 
      return { 
       ... 
      } 
     }, 

     methods: { 
      getVueItems: function(page) { 
       bus.$on('sort-param', function (sort) { 
        console.log(sort); 
       }) 
       ... 
      } 
     } 
    } 
</script> 

和我\資源添加var bus = new Vue(); \租入資產價值\ JS \ app.js

因此,它可以在任何地方訪問

我想排序參數(filterBySort方法,部件中的一個)到getVueItems方法(組分2)的顯示值

當被執行時,在控制檯中存在錯誤是這樣的:

Uncaught ReferenceError: bus is not defined

我該如何解決這個錯誤?

回答

5

您將需要從App.vue中導出變量總線,並將其導入任何您需要的地方。

我親自做的是創建一個專用的文件吧:bus.js

import Vue from 'vue' 
export default new Vue() 

並導入像這樣在需要的地方:

import bus from 'path/of/bus' 
<script> 
    export default{ 
     props:[...], 
     data(){ 
      return{ 
       ... 
      } 
     }, 
     methods:{ 
      filterBySort: function (sort){ 
       bus.$emit('sort-param', sort) 
       this.sort = sort 
       ... 
      } 
     } 
    } 
</script> 
+0

傾聽了什麼事件? – Dazzle

0

您需要確保定義變量的代碼var bus = new Vue();在使用此變量的代碼之前執行。

此外,請確保總線變量可由使用它的代碼訪問。

相關問題