我试图获取组件内部 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 的屏幕截图:
我尝试过的
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。
最佳答案
我建议采用不同的方法。在进入 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/