2017-01-05 54 views
1

我正在學習VueJs。我做了一個簡單的項目,你可以在這裏看到:VueJS連接到外部數據

var vuePosts = new Vue({ 
 
    el: '#vue-posts', 
 
    data: { 
 
    posts: [ 
 
     {title: 'title 1', body: 'message 1'}, 
 
     {title: 'title 2', body: 'message 2'} 
 
    ] 
 
    } 
 
})
<script src="https://unpkg.com/vue/dist/vue.js"></script> 
 

 
<div class="vue-test" id="vue-posts"> 
 
    <h1>Vue Test</h1> 
 
    <ul v-for="post in posts"> 
 
    <li> 
 
     <h1>{{post.title}}</h1> 
 
     <p>{{post.body}}</p> 
 
     <hr /> 
 
    </li> 
 
    </ul> 
 
</div>

正如你看到的,我只是做了V-並服用後的js文件。

我的問題是我應該怎麼做,我想從外部源中使用的數據,如

https://jsonplaceholder.typicode.com/posts

我怎樣才能將數據導入到我的data:並將它命名爲帖子?

回答

1

您可以創建一個方法,它將調用遠程API,獲取數據並將其分配給您的數據變量this.posts。從問題here啓發代碼,將類似於以下內容:

methods: { 
    getPosts: function() { 
     var that = this 
     $.ajax({ 
     url: 'https://jsonplaceholder.typicode.com/posts', 
     method: 'GET' 
     }).then(function (response) { 
     if(response.error) { 
      console.err("There was an error " + response.error); 
     } else { 
      console.log(response.posts); 
      this.posts = response.posts 
     } 
     }).catch(function (err) { 
     console.error(err); 
     }); 
    } 
    } 

,並且可以調用從安裝塊,其將獲取,當你的組件安裝指定的帖子這個方法。

mounted() { 
    this.getPosts() 
} 

您也可以對如何使用axios這是進行API一個HTTP客戶端調用

見工作筆here看看我answer

+0

之前什麼都謝謝你的時間saurabh。我試圖添加這些代碼給你,但是我一直無法使它工作。請看我的codepen http://codepen.io/fparedlo/pen/LxEqGX – noway

+0

@noway我已經對你的筆做了細微的修改,檢查[this](http://codepen.io/anon/pen/MJwWQR)。 – Saurabh

+0

非常感謝您的幫助我保留您的代碼並研究它。 – noway