【问题标题】:TypeError: Cannot read property '$auth' of undefined VuejsTypeError:无法读取未定义 Vuejs 的属性“$auth”
【发布时间】:2017-09-16 16:39:33
【问题描述】:

我正在使用 vuejs 2 和集成在其中的 laravel 5.4。我正在尝试构建一个使用 laravel 护照的身份验证服务。我已经能够登录用户,但问题出在 vue js 上。我创建了一个自定义 Auth 包来处理前端令牌。我收到 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
    }
    }
})
}

这是我的引导文件:

       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);
                });

        },

【问题讨论】:

  • 模块需要暴露install方法,像这样:stackoverflow.com/a/43193455/7636961另外,你导出一个接受参数Vue的函数,但你不会在之后调用这个函数。尝试导出一个常量或调用 o 函数,并将install 方法添加到您的插件中。
  • 也尝试了安装方法。还是不行。
  • 这是什么意思** 另外,您导出了一个接受参数 Vue 的函数,但之后您不调用此函数。 **
  • 我通过示例发布了一个答案。使用 const 代替函数。
  • 是的,我知道我已经标记正确

标签: javascript laravel vue.js vuejs2 laravel-5.4


【解决方案1】:

工作代码: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();
    }
});

【讨论】:

  • 你能解释一下我如何从另一个文件中使用它
  • 我编辑了答案来处理这个问题。在这种情况下,你必须通过 Vue 来安装函数。
【解决方案2】:

我找不到 self 的定义在哪里。 你可以用this.$auth替换'self.$auth',你应该使用箭头函数而不是then()的回调

【讨论】:

  • 你用箭头函数代替 then() 的回调函数吗?
  • 这有什么关系?然后得到回应。我试过了 。还是一样的错误
  • 在箭头函数中,this 指向父作用域。如果你使用箭头函数,this 将指向Vue.prototype
猜你喜欢
  • 2021-12-08
  • 2020-11-08
  • 2020-08-27
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2020-11-23
  • 1970-01-01
相关资源
最近更新 更多