繁体   English   中英

如何使用 Vuejs 和 Laravel 获取当前经过身份验证的用户 ID?

[英]How to get current authenticated user id using Vuejs and Laravel?

我使用 Vuejs 作为我的前端,我只想从 Laravel 获取当前登录用户的 ID 并显示它。 我该怎么做?

另一种选择是使用与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)
}

通过多种方式获取身份验证用户 ID 阅读更多

Auth::user()->id;

Auth::id();

通过 Vue.js

$http.get('api/user').then(response => {
   console.log(response.body);
})
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希望对某人有所帮助

在我的例子中 Laravel 9 我在 app.js 中没有 Vue object,因为它是通过 createInertiaApp 启动的。 所以我找到了一种方法,只修改 app.blade.php 和我的 Page.vue 文件。

简单地:

应用程序刀片 php:

window.user_id: {!! auth()->check()?auth()->user()->id:'null' !!}

Page.vue(最上面):

<script setup>
...
const user_id = window.user_id;
...

然后在我的 Page.vue 中,我可以在模板内的任何地方使用 {{ user_id }} 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM