如何在 axios 请求中使用 vue 路由器

ILy*_*Lya 2 javascript vue-router vuejs2

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

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

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

});
Run Code Online (Sandbox Code Playgroud)

我的 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';
Run Code Online (Sandbox Code Playgroud)

我的登录 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>
Run Code Online (Sandbox Code Playgroud)

我的路由文件如下:

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
});
Run Code Online (Sandbox Code Playgroud)

但是当我出现以下错误时:

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

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

或在组件内导入 VueRouter,但这两种方法都没有帮助。我做错了什么,如何让路由器工作。

小智 5

我假设您发布的代码就是全部,并且您遇到的错误可以在 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);
    });
Run Code Online (Sandbox Code Playgroud)

尽管 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);

    });
Run Code Online (Sandbox Code Playgroud)
  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);

     });
Run Code Online (Sandbox Code Playgroud)