【问题标题】:Using Vue.js components in PHP apps在 PHP 应用程序中使用 Vue.js 组件
【发布时间】:2018-08-01 12:55:33
【问题描述】:

我将 PHP 和 Vue.js 与 vue-router 一起使用。我有一个发送电子邮件的 php 表单处理程序。发送电子邮件时,我想将用户重定向到我的 vue 应用程序中的某个组件。有没有办法让它工作?我创建了一个组件Thankyou.vue,并希望以某种方式将其嵌入到我的 php 文件中。

if(mail($address, $msg, $headers)) {
    header("Location: http://mypage.com/thankyou");
}

【问题讨论】:

    标签: javascript php vue.js components vue-router


    【解决方案1】:

    我对 vue.js 不太熟悉,所以不要把我钉在 JS 部分:-)

    无论如何,您应该做的是使用 AJAX 将数据发布到 PHP 并返回 JSON 和正确的 HTTP 标头。

    在 JavaScript 中发布数据并处理响应承诺:

    this.$http.post('//someurl.bla', { key: value })
        .then((response) => {
          // show your thank you message
        })
        .catch(error => {
            console.log(error);
        });
    

    在 PHP 中处理错误:

    /**
     * exits the script and returns a HTTP 400 and JSON error message
     * @param str $msg error message
     */
    function dieError($msg) {
        http_response_code('400');
        echo json_encode(['error' => $msg]);
        exit;
    }
    
    // check form data
    if (!$_POST['parameter']) {
        dieError('Parameter "Parameter" is missing.');
    }
    // do stuff, build the mail content etc.
    
    // throw an error if the mail is not sent (note the !)
    if(!mail($address, $msg, $headers)) {
        dieError('Error sending mail');
    }
    
    // if the script arrives here, everything was fine, the status code will be 200 OK
    

    【讨论】:

    • 非常感谢。但是您认为在这部分:.then((response) => { // show your thank you message }) 我可以使用 vue.js 制作的路由重定向用户吗?
    • 如果没有问题,我应该用什么来代替//someurl.bla,我自己页面的url,对吧?
    • 您应该能够使用router.push() 进行重定向。 post()的第一个参数是你的PHP脚本的URL。
    • 我创建了一个方法并将其绑定到我的提交按钮。我更改了网址并添加了router.push()this.$http.post('../../index.php', { key: value }) 我仍然得到cannot read property 'post' of undefinedCannot POST,我应该改变什么?
    • cannot read property 'post' of undefined 表示未定义this.$http。没有看到你的 JS 代码,我什至无法猜测这是为什么。另外,正如我所说,我对 Vue.js 不太熟悉,但这个例子看起来很简单:codepen.io/tutelagesystems/pen/pjBbxQ 如果您仍然遇到问题,请在您的 JS 代码中发布另一个问题,并向 vue.js 专家寻求帮助: )
    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2018-05-27
    • 1970-01-01
    • 2017-05-10
    • 2020-02-05
    • 2019-04-08
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多