【发布时间】:2019-03-13 04:32:44
【问题描述】:
我使用 Vuejs 作为我的前端,我只想从 Laravel 获取当前登录用户的 id 并显示它。我该怎么做?
【问题讨论】:
标签: javascript php laravel authentication vue.js
我使用 Vuejs 作为我的前端,我只想从 Laravel 获取当前登录用户的 id 并显示它。我该怎么做?
【问题讨论】:
标签: javascript php laravel authentication vue.js
其他选项是使用与crsf 令牌相同的方式。
// header.blade.php
<meta name="user-id" content="{{ Auth::user()->id }}">
// main.js
Vue.prototype.$userId = document.querySelector("meta[name='user-id']").getAttribute('content');
// component
mounted() {
console.log(this.$userId)
}
【讨论】:
@if(Auth::check()) <meta name="user-id" content="{{ Auth::user()->id }}"> @endif
<meta name="user-id" content="{{ optional(Auth::user())->id }}">
this.$userId 填充到文本字段中?
通过多种方式获取auth用户idread more
Auth::user()->id;
Auth::id();
vue js
$http.get('api/user').then(response => {
console.log(response.body);
})
【讨论】:
<custom :user-id={{Auth::id()}}></custom>
If you are using authentication created by the
composer require laravel/ui
php artisan ui vue --auth
You can add to
// app.blade.php or whatever you have maybe master.blade.php
@if (Auth::check())
<meta name="user_id" content="{{ Auth::user()->id }}" />
@endif
Then in the app.js add
Vue.prototype.$userId = document.querySelector("meta[name='user_id']").getAttribute('content');
Now if you want to get the logged in user id and pass it to a hidden input field the first declare it as
<script>
export default {
props: ['app'],
data()
{
return{
user_id: this.$userId,
}
},
}
</script>
// Finally in your MyVueComponent.vue
<input type="hidden" name="user_id" v-model="user_id">
为了测试,尝试使用 type="text" 而不是 "hidden",你会发现它显示了当前的 id
【讨论】:
我需要将数据传递给我的 Header 组件,所以我想我可以分享一下我的做法
<fronend-header :current-user="{{ json_encode(['isLoggedIn'=>auth()->check() ? true : false, 'user'=>auth()->check() ? auth()->user() : null]) }}" />
在 vuejs 方面
<script>
export default {
name: "frontend-header",
props: {
currentUser: {
type: Object,
required: true
}
}
};
</script>
尚未在登录状态下尝试过,但如果需要,我会做任何必要的更改。
【讨论】:
您好,我尝试了上述解决方案,但由于还没有登录用户而出现错误。 Uncaught TypeError: Cannot read property 'getAttribute' of null
我添加了@else,然后就可以了。
@if (Auth::check()) <meta name="user_id" content="{{ Auth::user()->id }}" />@else <meta name="user_id" content="0" /> @endif希望对某人有所帮助
【讨论】: