javascript - 无法从 Vue 组件获取正确的 Prop 值

标签 javascript authentication vue.js vuejs2 vue-component

我试图获取组件内部 props 的值,但返回的值不正确。

App.vue

<template>
    <v-app>
    <router-view :authentication="auth"></router-view>
</template>

<script>
    import auth from '../auth.js';
    export default {
      data       : () => ({
          auth           : auth
      }),
      mounted: function () {
          this.$nextTick(function () {
              auth.check()
          })
      }
    }
</script>

Dashboard.vue(呈现为路由器 View )

<template>
    <h1>You're Logged In!</h1>
</template>

<script>
    export default {
        props: ['authentication'],
        mounted: function() {
            this.$nextTick(function () {
                console.log(this.authentication.user.authenticated) // Returns false (should be true)
                }
            )
        }
    }
</script>

auth.js

export default {
    user: {
        authenticated: false,
        profile: null
    },
    check() {
        let token = localStorage.getItem('id_token')
        if (token !== null) {
            Vue.http.get(
                'api/user?token=' + token,
            ).then(response => {
                this.user.authenticated = true
                this.user.profile = response.data.user
            })
        }
    }
}

Dashboard.vue 中 console.log(this.authentication.user.authenticated) 的结果返回为 false,但 Vue devtools 指示该值应为 true(这是应该返回的内容)。

这是通过 Vue devtools 在我的 Dasboard.vue 组件中的 Prop 的屏幕截图: enter image description here

我尝试过的

1) 我尝试将 auth.js 中的 user 对象的值从 false 更改为 true 然后我在 Dashboard.vue 中得到正确的输出。然而,这并不好,因为 check() 函数应该更新 auth.js 中的 user 对象的值。

2) 我已经在 Dashboard.vue 中记录了 this.authentication 的结果,我可以清楚地看到嵌套对象 user.authenticated 为 true,但 console.log(this.authentication.user.authenticated) 的结果由于某种原因仍然为 false。

这是 console.log(this.authentication) 的记录结果的屏幕截图: enter image description here

最佳答案

我建议采用不同的方法。在进入 Vue 之前检查授权,然后根据用户是否获得授权,设置适当的路由器路径。

这需要从 auth 中的 check 方法返回一个 promise。

check(){
  return new Promise((resolve, reject) => {
    // do your authentication and set user.authenticated appropriately
    resolve(this.user)
  })
}

然后你的主脚本看起来像这样:

import Vue from "vue";
import App from "./App";
import router from "./router";
import auth from "./auth";

auth.check().then(user => {
  if (!user.authenticated) {
    router.push("/NotAuthorized");
  }

  new Vue({
    el: "#app",
    router,
    template: "<App/>",
    components: { App }
  });
});

这是一个working example .

关于javascript - 无法从 Vue 组件获取正确的 Prop 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47742558/

相关文章:

javascript - 如何在 iPad 中通过 javascript 停止 Youtube 视频(不是 HTML5)

javascript - JavaScript 中的多线程或异步代码如何工作?

javascript - 访问属性名称位于变量中的对象属性

java - HTMLUnit 密码设置问题

java - Tomcat 使用 BASIC auth 而不是 FORM auth

javascript - 在vue js中使用axios post方法下载文件

javascript - 当输入仍然集中时,jquery 代码不执行

authentication - OpenVPN CE 与 Google 安全 LDAP 集成中的 TLS 错误

vue.js - Vuetify - 自定义

javascript - 你如何在 Vue 中条件绑定(bind) v-model?