javascript - 如何在axios请求中使用vue router

标签 javascript vuejs2 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
});

但是当我有以下错误时:

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

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

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

最佳答案

我假设您发布的所有代码都是存在的,并且您遇到的错误可以在 Login Vue 组件的这个 block 中找到,您在其中引用了 $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 是访问路由器依赖项的正确语法,但在回调函数中调用它,使用正则函数表达式,创建一个新的绑定(bind)到“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);

     });

关于javascript - 如何在axios请求中使用vue router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43980917/

相关文章:

javascript - 根据用户的角色在菜单中显示不同的内容

javascript - Jquery 显示/隐藏更多数据

javascript - 使用 Vue CLI - 如何更新、删除和查看所有可用插件

javascript - 将 div 的中心定位到页面上的给定坐标

javascript - KnockoutJS observableArray 未初始化

javascript - 在vue js中访问通过eventbus发送的对象的值

javascript - 如何将vue.js计算数据插入到表单数据中?

javascript - Vue 取数据前的未定义数据

javascript - 有没有一种很好的方法可以使用 Vue 路由器将 props 传递给父组件?

nuxt.js - Nuxt 3 在中间件中使用可组合性