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数组中,并将显示在页面上。