2017-02-28 116 views
0

假設我有一個App.vueQuery.vueResult.vue是它的孩子。在vue.js中的組件之間傳遞數據的最佳方式是什麼?

和路由器看起來是這樣的:

import Query from '@/components/Query' 
import Result from '@/components/Result' 

export default new Router({ 
    routes: [ 
    { 
     path: '/', 
     name: 'query', 
     component: Query 
    }, { 
     path: '/result', 
     name: 'result', 
     component: Result 
    } 
    ] 
}) 

有在Query.vue一個按鈕,點擊後,它會發送一個POST請求API:

this.$http.post(url, { 
    arg1: arg1, 
    arg2: arg2 
    }).then(function (response) { 
    data = response.data 

    // I want to do something like: 
    this.$router.push({path: 'result', payload: data}) 

    }, function (response) {}) 

然後在Query.vue,我可以處理​​。

但似乎不可能。我應該使用store來製作它嗎?

this.$http.post(url, { 
    data: "some data" 
    }).then(function (response) { 
    store.store(response.data) 
    this.$router.push({path: 'result'}) 
    }, function (response) {}) 

回答

0
  1. 如果你只需要通過一些數據從父一個定向到子 - 使用的道具。
  2. 如果您需要從孩子的數據傳遞給父 - 使用事件
  3. 如果你需要保持在多個組件(未父/子)同步一些數據 - 使用VUEX
+0

我只需要通過一些數據一個方向,但是'Result.vue'不是'Query.vue'的子節點。那麼使用'vuex'? – HungryMilk

+0

是的。這將是最好的方式,並由Vue推薦 –

+0

明白了。非常感謝! – HungryMilk

相關問題