【问题标题】:Async post with VueJS and Axios使用 VueJS 和 Axios 进行异步发布
【发布时间】:2017-11-07 16:26:32
【问题描述】:

我在 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,当我进行页面刷新时,我会在页面顶部看到应有的新帖子。

但是在请求完成后,如何让页面异步加载新帖子?

【问题讨论】:

  • 如果发布请求成功,那么我只需将发布的数据插入到带有 Vue 的页面中,在 then 回调中。
  • 你能用一个小代码sn-p详细说明一下吗?我现在才使用 Vue 大约一个月。
  • 是的。哪个网址获取帖子? '/wp-json/wp/v2/categories'?
  • /wp-json/wp/v2/posts?context=edit&_embed=true
  • 那么您列出帖子的组件与您创建帖子的组件不同?因为我在您的示例中没有看到 get 请求。

标签: javascript rest api vue.js axios


【解决方案1】:

如果您的帖子创建成功,这意味着如果您向帖子端点发出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 = '';
  }

该组件的父组件将捕获包含数据的事件。继续发出事件或传递道具,直到到达显示列表的组件。进入列表组件后,将新帖子推送到帖子数组中,它将显示在页面上。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2018-11-25
    • 2019-11-10
    相关资源
    最近更新 更多