Javascript 无法从Vue组件获取正确的道具值
我试图获取组件内部道具的值,但返回的值不正确 App.vueJavascript 无法从Vue组件获取正确的道具值,javascript,authentication,vue.js,vuejs2,vue-component,Javascript,Authentication,Vue.js,Vuejs2,Vue Component,我试图获取组件内部道具的值,但返回的值不正确 App.vue <template> <v-app> <router-view :authentication="auth"></router-view> </template> <script> import auth from '../auth.js'; export default { data : () =>
<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中console.log(this.authentication.user.authenticated)
的结果返回为false
,但vue开发工具指示该值应为true
(这是应返回的值)
以下是通过vue devtools在myDasboard.vue
组件中的道具的屏幕截图:
我试过的
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)
的结果出于某种原因仍然是假的
以下是console.log(this.authentication)
的记录结果的屏幕截图:
我建议采用不同的方法。在进入Vue之前检查授权,然后根据用户是否获得授权,设置适当的路由器路径 这需要从
auth
中的check
方法返回承诺
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 }
});
});
从“Vue”导入Vue;
从“/App”导入应用程序;
从“/router”导入路由器;
从“/auth”导入身份验证;
auth.check().then(用户=>{
如果(!user.authenticated){
路由器推送(“/NotAuthorized”);
}
新Vue({
el:“应用程序”,
路由器,
模板:".仪表板的挂载的生命周期处理程序。vue
在已验证的设置为true之前启动。下一步不会解决这个问题,vue生命周期大约为15毫秒,ajax调用可能需要更长的时间。这是有意义的@Bert。有什么办法解决这个问题吗您确实想做什么?我想让我的mounted
生命周期处理程序能够在Dashboard.vue
中读取最新版本的authentication
道具。为什么要在mounted中执行此操作?
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 }
});
});