如何在axios请求中使用vue router

新手上路,请多包涵

我有以下 app.js 文件作为主要的 Vue 组件。

 import './bootstrap';
import router from './routes';

new Vue({
    el: '#app',
    router: router

});

我的 bootstrap.js 如下

import Vue from 'vue';
import VueRouter from 'vue-router';
import axios from 'axios';

// Global variable for API access
window.hostname = 'https://city.molotex.ru/cgi-bin/citygate.py?';

// Global variable for VueJS
window.Vue = Vue;

// Vue router
Vue.use(VueRouter);

//Vue Resource
var VueResource = require('vue-resource');
Vue.use(VueResource);

// axios
window.axios = axios;

window._ = require('lodash');

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap-sass');
} catch (e) {}

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

我的登录 Vue 如下:

 <template>

                        <form class="form-horizontal" role="form" method="POST" action="login">

                            <div class="form-group">
                                <label for="email" class="col-md-4 control-label">Логин (email)</label>

                                <div class="col-md-6">
                                    <input id="email" type="email" class="form-control" name="email" v-model="email">
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="password" class="col-md-4">Пароль</label>

                                <div class="col-md-6">
                                    <input id="password" type="password" class="form-control" name="password" v-model="password">
                                </div>
                            </div>

                            <div class="form-group">
                                <div class="col-md-8 col-md-offset-4">
                                    <button type="button" v-on:click="login" class="btn btn-primary">
                                        Login
                                    </button>
                                </div>
                            </div>
                        </form>

</template>

<script>
    export default {
        mounted() {
            console.log('Component is mounted.');
        },

        data() {
            return {
                email: '',
                password: '',

                response_key: ''
            }
        },

        methods: {
            login() {
                let self = this;

                axios.post('/login', {
                    email: this.email,
                    password: this.password
                }).then(function (response) {
                    self.response_key = response.data.result;
                    this.$router.push('/user_main_page');
                        console.log(response);
                }).catch(function (error) {
                        console.log(error);
                });
            }
        }
    }
</script>

我的路线文件如下:

 import VueRouter from 'vue-router';

let routes = [
    {
        path: '/',
        component: require('./components/Example.vue')
    },
    {
        path: '/about',
        component: require('./components/About.vue')
    },
    {
        path: '/login',
        component: require('./components/Login.vue')
    },
    {
        path:'/user_main_page',
        component: require('./components/UserMainPage.vue')
    }
];

export default new VueRouter({
    routes
});

但是当我有以下错误时:

类型错误:无法读取 app.js:4341 处未定义的属性“$router”

我尝试了不同类型的路由,例如:使用全局路由变量作为:window.router = VueRouter;

或在组件内导入 VueRouter,但这两种方法都无济于事。我做错了什么,如何让路由器工作。

原文由 ILya 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答

我假设您发布的代码是所有的,并且您遇到的错误可以在 Login Vue 组件的这个块中找到,您在其中引用 $router 变量。

     axios.post('/login', {

        email: this.email,
        password: this.password

    }).then(function (response) {

        self.response_key = response.data.result;
        this.$router.push('/user_main_page');
        console.log(response);

    }).catch(function (error) {

        console.log(error);
    });

虽然 this.$router 是访问路由器依赖项的正确语法,但在回调函数中调用它,使用正则函数表达式,创建一个新的绑定到“this”对象而不是 Vue 对象本身。

你有两种选择来解决这个问题:

  1. 将对象引用存储到回调函数外部的变量 vm 中。
     const vm = this;
    axios.post('/login', {

        email: this.email,
        password: this.password

    }).then(function (response) {

        self.response_key = response.data.result;
        vm.$router.push('/user_main_page');
        console.log(response);

    }).catch(function (error) {

        console.log(error);

    });

  1. 创建函数时使用箭头语法,这样您对“this”的引用就不会被覆盖。 (参考: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
      axios.post('/login', {
         email: this.email,
         password: this.password
     }).then(response => {

         self.response_key = response.data.result;
         this.$router.push('/user_main_page');
         console.log(response);

     }).catch(error => {

         console.log(error);

     });

原文由 ecnopdev 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题