【问题标题】:Axios put request issueaxios put 请求问题
【发布时间】:2023-03-12 15:25:02
【问题描述】:

我目前正在建立一个博客,但我被困在编辑文章部分。

所以,在编辑文章页面上,我使用 v-model 来从 vue 存储中检索数据:

<form action="/http://localhost:4000/articles" method="POST">       
  <div role="button" type="submit" @click="submitArticle">Save</div>

    <div class="article-writing__inner" v-for="article in articles">

     <div class="title-offset">Title</div>
      <input class="input-title"  type="text" v-model="article.title"/>

     <tinymce id="d1"v-model="article.text"></tinymce>

   </div>
</form>

我为 v-for 循环使用计算属性:

computed: {
    articles() {
       return this.$store.state.articles
      }
 }

最后我使用 axios 将数据发送到 API,如下所示:

methods: {
        submitArticle() {
            axios.put('http://localhost:4000/articles/:id', {
                title: article.title,
                text: article.text,
            })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
        }
    }

正如我所料,我无法访问 axios 中的 store (v-model) 数据。在创建文章模板中,我使用了如下所示的 v-model 并成功使用title: this.title 发布。

data() {
  return {
    title: "",
    text: ""
  }
}

如何将 v-model 从本地组件数据函数绑定到 axios?或者这是另一种方法吗?

感谢您的宝贵时间:)

【问题讨论】:

    标签: javascript vue.js axios vuex


    【解决方案1】:

    在对 axios 的 put 调用中,Article 未设置为任何内容。在 axios 调用中获取状态值的一种方法是执行以下操作。

    submitArticle() {
        let vm = this;
        axios.put('http://localhost:4000/articles/:id', {
                title: vm.article.title,
                text: vm.article.text,
            })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
        }
    }
    

    这都是关于 axios 调用上下文中“this”的范围。

    【讨论】:

    • 感谢您的回复!试试你的方法,我有一个Uncaught TypeError: Cannot read property 'title' of undefined
    • 你的数据是不是像 data() { article: { title: '', text: '' } }
    • 文章数组在 Vuex 存储中,所以当我在编辑文章页面时,字段由它们在存储中的值填充。如果我将文章数组放在标题为“”的数据组件中,就像你说的那样,字段将为空
    • 我想修改用axios绑定在store中的数据,而不是某个组件的本地数据
    • 你需要通过一个动作和突变来完成它。在操作中调用 axios,因为这是一个异步调用。
    猜你喜欢
    • 2019-11-20
    • 2019-05-20
    • 2022-12-21
    • 2021-10-05
    • 2020-01-12
    • 2018-05-20
    • 1970-01-01
    • 2018-12-26
    • 2020-06-22
    相关资源
    最近更新 更多