2017-09-03 84 views
0

如何將數據發送到Vue.js中的組件?我在按鈕點擊事件中得到了服務器的響應,現在我想將此響應發送到組件並使用v-forlist上顯示。如何向vue js中的組件發送數據?

這裏是我的代碼:

var store = new Vuex.Store({ 
    state: { 
     Item: [] 
    }, 
    mutations: { 
     getItems: function (state) { 

     } 

    }, 
    actions: { 
     fetchData:function (context) { 
      Vue.http.get('data.json').then(function(response){ 
      alert('dd') 
}, function(error){ 
    console.log(error.statusText); 
}); 

     } 
    } 
}) 

var httprequest = Vue.extend({ 
    "template": '#http_template', 
    data: function() { 
     return { 
      items: store.state.Item 
     } 
    }, 
    methods: { 
     fetchData: function() { 
      store.dispatch('fetchData') 
     }, 

    } 
}) 

Vue.component('httprequest', httprequest); 

var app = new Vue({ 
    el: '#App', 
    data: {}, 


}); 
+0

[如何在VUE js中的組件之間共享數據(當創建列表時)](https://stackoverflow.com/questions/46015442/how-to-share-data-between-components-in-vue -js-while-creating-list) – bbsimonbb

回答

1

你已經幾乎完成所有的事情。唯一缺少的是在獲取數據後,您不會將其分配給state.Item。請檢查以下代碼:

var store = new Vuex.Store({ 
    state: { 
     Item: [] 
    }, 
    mutations: { 
     getItems: function(state, items) { 
     items.forEach(function(item) { 
      state.Item.push(item) 
     }) 
     } 
    }, 
    actions: { 
     fetchData: function(context) { 
     Vue.http.get('data.json').then(function(response) { 
      context.commit('getItems', response.data) 
     }, function(error) { 
      console.log(error.statusText); 
     }); 
     } 
    } 
    }) 

工作示例可以找到here

1

一般VUE如下原則,即通過數據屬性和多達通過事件而來的DOM樹下來。例如參見https://vuejs.org/v2/guide/index.html#Composing-with-Components

因此,要將數據導入組件,請在組件中定義屬性myProp,並在使用組件時通過v-bind:myProp="myData"將其綁定。

要從組件中取回數據,請使用this.$emit('myUpdateEvent', myUpdatedData)並使用v-on:myUpdateEvent="myUpdateHandler"收聽活動。

+0

請刪除這個anwser。我使用vuex不發射 – naveen

+0

請檢查我的plunker.I不使用發射或廣播 – naveen

+0

我指出的原則是非常相關的你的用例:如果你有一個通用列表組件,你不想直接在它內部綁定Vuex數據,而是將它綁定到父組件,並將其作爲屬性傳遞給列表。 –

1

您不會將數據發送到組件。您可以設置無功管道,並在需要時移動數據。在你的情況下,使用vuex,你想在你的組件的數據上註冊store.state.items。

如果需要,您可以使用道具,但您仍然需要在父級數據中進行註冊。如果你的組件是一個單獨的,只用於這個頁面,你最好直接在組件的數據中註冊你需要的東西。