2017-06-06 53 views
0

我在VueJS異步後與VueJS和愛可信

created() { 
    axios.get('/wp-json/wp/v2/users/' + portal.user.id + '?context=edit', {headers: {'X-WP-Nonce': portal.nonce}}) 
    .then(response => { 
    this.user = response.data; 
    }) 
    .catch(e => { 
    this.errors.push(e); 
    }); 

    axios.get('/wp-json/wp/v2/categories') 
    .then(response => { 
    this.terms = response.data; 
    }) 
    .catch(e => { 
    this.errors.push(e); 
    }); 
}, 

methods: { 
    createPost: function() { 

    let title = this.new_post_title; 
    let content = this.new_post_content; 
    let tags = this.new_post_tags; 
    let status = this.status; 

    let data = { 
     'title': title, 
     'content': content, 
     'status': status, 
    }; 

    axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}}) 
    .then(response => { 
     console.log(response); 
    }) 
    .catch(e => { 
     this.errors.push(e); 
     console.log(this.errors); 
    }); 

    this.new_post_title = ''; 
    this.new_post_content = ''; 
    this.new_post_tags = ''; 
    } 
}, 

一切工作與請求的方法和創建的屬性,數據被髮布到WordPress的,當我做了刷新頁面,我得到的頁面頂部的新帖子應該是這樣。

但是,我該如何着手讓頁面在請求完成後異步加載新文章?

+0

如果發佈的請求成功,那麼我只需將發佈的數據插入到帶'Vue'回調函數的Vue頁面中。 –

+0

您能否詳細說明一些小代碼片段?我只用了一個月左右的Vue。 –

+0

是的。哪個網址獲取帖子? ''/ WP-JSON/WP/V2/categories''? –

回答

0

如果您的帖子被成功創建,這意味着如果您向帖子終端發出get請求,您將獲得新創建的帖子。就像你在刷新頁面一樣。所以我的意思是直接將新帖子插入到客戶端的頁面中,在成功的發佈請求之後。沒有得到要求。

我不知道你的組件層次結構,或者你是否使用Vuex。但是,從創建該帖子的組件中,您將包含新帖子數據的事件$emit

createPost: function() { 

    let title = this.new_post_title; 
    let content = this.new_post_content; 
    let tags = this.new_post_tags; 
    let status = this.status; 

    let data = { 
     'title': title, 
     'content': content, 
     'status': status, 
    }; 

    axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}}) 
    .then(response => { 
     console.log(response); 
     this.$emit('new-post',data) 
    }) 
    .catch(e => { 
     this.errors.push(e); 
     console.log(this.errors); 
    }); 

    this.new_post_title = ''; 
    this.new_post_content = ''; 
    this.new_post_tags = ''; 
    } 

此組件的父節點將捕獲包含數據的事件。繼續發佈事件或傳遞道具,直到到達顯示列表的組件。進入列表組件後,將新帖子推入posts數組中,並將顯示在頁面上。