【问题标题】:VueJS Vuex Axios cURL API for Wordpress用于 Wordpress 的 VueJS Vuex Axios cURL API
【发布时间】:2022-12-01 12:26:05
【问题描述】:

我正在使用 Vuex 进行所有 API 调用,并且从一开始,文档就给出了用于显示帖子的 HTTP 请求示例。但是当涉及到 CRUD 时,示例中提到的是 cURL 请求而不是 HTTP 请求。这是我第一次使用 API,我不知道从现在开始我调用 API 的语法/方式是否可用于 cURL API。到目前为止,这是我的代码。

state: {
    posts: [],
    cats: [],
  },
  actions: {
    async fetch({ commit }) {
      try {
        const data = await axios.get(
          "http://localhost:8080/wp-json/wp/v2/posts"
        );
        const data2 = await axios.get(
          "http://localhost:8080/wp-json/wp/v2/categories"
        );
        commit("SET_posts", data.data);
        commit("SET_cats", data2.data);
      } catch (error) {
        alert(error);
        console.log(error);
      }
    },
  },
  mutations: {
    SET_posts(state, posts) {
      state.posts = posts;
    },
    SET_cats(state, cats) {
      state.cats = cats;
    },
  },

以及删除帖子的 API 调用示例

curl -X DELETE https://example.com/wp-json/wp/v2/posts/<id>

我想我必须使用至少一个参数/参数创建另一个函数,因为我们必须传递 id 才能使 api 调用工作。

这是我第一次使用 Vuex,也是我第一次使用 API,抱歉,如果我的要求很明显......

【问题讨论】:

    标签: api vue.js curl vuex axis


    【解决方案1】:

    添加新操作:

    actions: {
      async fetch({ commit }) {
        ...
      },
      async deletePost({ dispatch }, postId) {
        await axios.delete(
          `http://localhost:8080/wp-json/wp/v2/posts/${postId}`
        );
        // fetching posts again after delete is completed
        await dispatch('fetch');
      },
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2018-06-03
      • 2018-12-31
      • 2020-12-23
      • 2020-02-15
      • 2021-10-24
      • 2018-08-23
      • 2021-04-11
      • 2017-06-30
      相关资源
      最近更新 更多