【问题标题】:Cannot get the right props value from Vue Component无法从 Vue 组件中获取正确的 props 值
【发布时间】:2018-05-24 08:44:14
【问题描述】:

我正在尝试获取组件内部 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(呈现为路由器视图)

<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 开发工具指示该值应为true(应返回的值)。

这是我的 Dasboard.vue 组件中的道具通过 Vue devtools 的屏幕截图:

我的尝试

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

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

这是console.log(this.authentication)的记录结果截图:

【问题讨论】:

  • Dashboard.vuemounted 生命周期处理程序正在触发 before authenticated 设置为 true。 nextTick 不会解决这个问题,Vue 生命周期大约为 15 毫秒,而 ajax 调用可能需要更长的时间。
  • 这很有意义@Bert。任何想法如何解决这个问题?
  • 你到底想做什么?
  • 我希望我的 mounted 生命周期处理程序能够读取 Dashboard.vueauthentication 属性的最新版本
  • 为什么要在mounted中这样做?

标签: javascript authentication vue.js vuejs2 vue-component


【解决方案1】:

我建议采用不同的方法。在你进入 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

【讨论】:

    猜你喜欢
    • 2018-07-22
    • 2016-04-01
    • 2022-11-11
    • 2017-05-21
    • 2022-11-13
    • 1970-01-01
    • 2022-01-17
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多