javascript - 类型错误 : Cannot read property '$auth' of undefined Vuejs

标签 javascript laravel vue.js vuejs2 laravel-5.4

我正在使用集成了 laravel 5.4 的 vuejs 2。我正在尝试构建一个使用 laravel passport 的身份验证服务。我已经能够登录用户,但问题出在 vue js 上。我创建了一个自定义 Auth 包来处理前端 token 。我收到错误消息 Cannot read property 'setToken' of undefined

我的授权包是这样的:

export default function (Vue){
Vue.auth = {
    // set token 
    setToken : (token , expires_in) =>{
    localStorage.setItem('token' , token);
    localStorage.setItem('expires_in' , expires_in)
    },
    // get token
    getToken : ()=>{

    },

    // destroy token


    // isAuthenticated
    isAuthenticated : ()=>{
    if(this.getToken())
    {
        return true
    }
    return false
    }
}
Object.defineProperties(Vue.prototype , {
    $auth : {
        get: ()=>{
        return Vue.auth
    }
    }
})
}

这是我的 Bootstrap 文件:

       window._ = require('lodash');

    /**
     * We'll load jQuery and the Bootstrap jQuery plugin which provides support
     * for JavaScript based Bootstrap features such as modals and tabs. This
     * code may be modified to fit the specific needs of your application.
     */
      window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');

/**
 * Vue is a modern JavaScript library for building interactive web interfaces
 * using reactive data binding and reusable components. Vue's API is clean
 * and simple, leaving you to focus on building your next great project.
 */

window.Vue = require('vue');

import VueRouter from 'vue-router';

import Auth from './packages/auth/Auth.js';

Vue.use(VueRouter);
Vue.use(Auth);

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

axios.defaults.baseURL = 'http://localhost/iAttendanceLaravel/public/';



/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo'

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: 'your-pusher-key'
// });

最后这是我在 login.vue 文件中的登录方法:

  methods: {
        login: function () {

            var data = {
                client_id : 2,
                client_secret : '8WCDtW3wKeeNUBgwHviFoX7JmaVPU0HjFto9kwqv',
                grant_type     : 'password',
                username : this.loginForm.email,
                password : this.loginForm.password
            };

            axios.post('/oauth/token', data)
                .then(function (response) {
                    console.log(response);
                    self.$auth.setToken(response.body.access_token , response.body.expires_id + Date.now());
                })
                .catch(function (error) {
                    console.log(error);
                });

        },

最佳答案

工作代码:https://jsfiddle.net/wostex/63t082p2/30/ (最少的功能,只是为了展示它是如何工作的)

const auth = {
    setToken : () => {
      console.log('inside setToken');
    },
    install: function(Vue){
      Object.defineProperty(Vue.prototype, '$auth', {
        get () { return auth }
      })
    }
};

Vue.use(auth);

new Vue({
    el: '#app',
    mounted() {
      this.$auth.setToken();
    }
});

关于javascript - 类型错误 : Cannot read property '$auth' of undefined Vuejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43512856/

相关文章:

laravel - 没有足够的权限在 Algolia Laravel 中添加对象

php - 与 laragon 一起安装的 Laravel 项目在谷歌浏览器中强制使用 https

vue.js - 在重复内容区域添加 <slot>

javascript将字符串解析为对象或JSON

javascript - TinyMCE、save_callback 和 onSaveContent

javascript - 在滚动 Bootstrap 3 上更改 Logo

node.js - Laravel 5.4 app.js 代码混淆

javascript - ChartWrapper 不显示图表

vue.js - 具有 v-once 效果的功能组件

javascript - vuex-持久状态 : How can I use getters with vuex-persistedstate?