【问题标题】:How to get url from :href in vue and axios?如何从 vue 和 axios 中的 :href 获取 url?
【发布时间】:2020-10-21 22:56:03
【问题描述】:

我尝试使用 vue 和 axios 从 :href 元素发送帖子,但我不知道如何从 :href 填充 axios url 参数。

我试试这个:

            <div id="follow">
                <a :href="'{% url 'follow' recipe.added_by.id %}'" @click="followUser()">Obserwuj</a>
            </div>

Href 元素填充了 Django 模板标签,并且工作正常。

我的vue和axios代码:

  methods: {
        followUser() {
            axios.post()
                .then(response => {
                    console.log(response.data);
                })
                
                .catch(errors => {
                    if (errors.response.status == 401){
                        window.location = '/login';
                    }
                });
        }
    },

当我点击链接时,出现错误:“TypeError:errors.response is undefined”

【问题讨论】:

  • 渲染出来的 HTML 是什么样子的?我希望 document.querySelector("#follow a").getAttribute("href") 在任何框架中

标签: javascript vue.js axios


【解决方案1】:

您不能通过 URL 发送 POST 请求,因为 post 参数不是通过 URL 发送的,但您可以使用替代解决方案,而不是使用链接来使用看起来像链接且采用表单的按钮:如何使按钮看起来像一个链接?使按钮看起来像一个链接。

祝你有美好的一天,希望对你有帮助。

【讨论】:

    【解决方案2】:

    在你的情况下,你可以在 ES6 中使用解构来获取目标元素:

     <button :href="'{% url 'follow' recipe.added_by.id %}'" @click="followUser">Obserwuj</button>
    
     ////
    
     methods: {
            followUser({ target }) {
                const url = target.getAttribute('href')
                axios.post(url) 
                    .then(response => {
                        console.log(response.data);
                    })
                    .catch(errors => {
                        if (errors.response.status == 401){
                            window.location = '/login';
                        }
                    });
            }
        },
    

    【讨论】:

      猜你喜欢
      • 2013-07-07
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2021-09-22
      • 2019-07-03
      • 1970-01-01
      • 2017-05-30
      • 2020-09-14
      相关资源
      最近更新 更多