2017-06-16 114 views
0

我有兩個組成部分Vue公司JS通過總線共享的數據不能正常工作

1.Search

export default { 
    mounted() { 
    console.log('Component mounted :: SearchGas') 
    }, 
    data() { 
    return { 
     form: new Form({ 
     distributor: '', 
     supplier: '' 
     }) 
    }; 
    }, 
    methods: { 
    onSubmit() { 
     let str = "distributor=" + this.form.distributor + "&supplierId=" + this.form.supplier; 
     let baseUrl = 'wfengine/price_filter_gas_1/'; 

     Bus.$emit('cards_search_query', baseUrl + '?' + str); 

     //Here I am updating Vikram 
     this.$router.push('/results/' + encodeURIComponent(baseUrl + '?' + str)); 
    } 
    } 
} 

3.結果

export default { 
    mounted() { 
    console.log('Component mounted :: Results'); 
    // console.log(this.$route.params.items); 
    Bus.$on('cards_search_query', function(query) { 
     console.log(query); 
    }) 
    }, 
    data() { 
    return { 
     cardList: [], 
     form: new Form({}), 
     dataList: [], 
     createCardList 
    }; 
    } 
} 

在我Appjs,我我打電話給我正在做的所有文件

window.Bus = new Vue({});

問題

當我重定向到結果頁,我沒有得到基於所提供的信息是,要在控制檯中看到任何 值

+0

您的應用程序SPA是否可以在兩個組件之間完全重新加載? –

+0

@MU水療中心,如果你想要的話,我可以添加routes.js頁面 – Vikram

+0

原因是你的'結果'組件不存在*在你的'放出'時在DOM中。兩者都需要加載,Vue中沒有堆棧事件。 – Elfayer

回答

0

你好,正如MU解釋的那樣,這就是我解決它的方法。

我安裝VueX

NPM安裝vuex --save

然後在我的應用程序。JS頁面是父實例

import Vuex from 'vuex'; 

Vue.use(Vuex); 
const store = new Vuex.Store({ 
    state: { 
    cards_search_query: 'ss' 
    } 
}); 

然後在我的搜索頁面

methods : { 

      onSubmit(){ 

       let str = "distributor="+this.form.distributor+"&supplierId="+this.form.supplier; 

       let baseUrl = 'wfengine/price_filter_gas_1/'; 

       this.$store.state.cards_search_query = baseUrl+'?'+str; 
       //Here I am updating Vikram 
       this.$router.push('/results/'); 

      } 
     } 

,在我結果頁面

mounted() { 
     console.log('Component mounted :: Results'); 
     console.log(this.$store.state.cards_search_query); 
    }, 

請注意

this.$store.state.cards_search_query = baseUrl+'?'+str; 

雖然使用Vuex可能會超出這個簡單的任務。

2

可能的原因其他組件僅在事件發出時不在DOM中,因此它不會對事件做出反應。

在這種情況下,我會建議使用帶參數的路由,所以第一個組件會觸發路由+str或類似的東西,第二個組件會從路由中獲取參數。

其他的方法,但在我看來這不是很好,在Vuex中使用Vuex和存儲查詢,所以第一個組件將提交查詢Vuex和第二個將從Vuex得到它。但是,我會建議第一個解決方案。

如果您有一些需要在組件之間共享但實際上不想公開的數據(但請記住,在前端,一切或多或少暴露出來,只是需要付出努力的問題),您理論上可以使用LocalStorage作爲路由參數/ Vuex的替代解決方案。

另一種解決方案(如此多)是以這種方式解決你的路線,你會有一些父組件,例如SEARCH-PARENT <router-view>和2個嵌套路線與您的組件SEARCH-DIALOG &搜索結果。對話框會在現在發出事件,父母會做出反應,然後在路由改變時將它傳遞給結果。 也許這樣?

+0

是的我的應用程序工作正常,通過路由本身發送的參數,但想一想。就像我想在兩個不同的路線上分享不應該在url上傳遞的數據一樣,我真的需要使用VueX嗎? – Vikram

+0

也許他也可以使用路由器[道具](https://router.vuejs.org/en/essentials/passing-props.html)。 – Elfayer

+0

我已經添加了其他解決方案。也許你會喜歡他們中的任何一個。 –