【发布时间】: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.js 中user 对象的值。
2) 我在Dashboard.vue 中记录了this.authentication 的结果,我可以清楚地看到嵌套对象user.authenticated 为真,但由于某种原因console.log(this.authentication.user.authenticated) 的结果仍然为假。
【问题讨论】:
-
Dashboard.vue的mounted生命周期处理程序正在触发 beforeauthenticated设置为 true。nextTick不会解决这个问题,Vue 生命周期大约为 15 毫秒,而 ajax 调用可能需要更长的时间。 -
这很有意义@Bert。任何想法如何解决这个问题?
-
你到底想做什么?
-
我希望我的
mounted生命周期处理程序能够读取Dashboard.vue中authentication属性的最新版本 -
为什么要在mounted中这样做?
标签: javascript authentication vue.js vuejs2 vue-component