简体   繁体   中英

How can I use auth on vue component ? (Vue.JS 2)

My view blade like this :

@if (Auth::user())
    <favorite :id="{{ $store->id }}"></favorite>
@else
    <a href="{{url('/login?red='.Request::path())}}" class="btn btn-block btn-success">
        <span class="fa fa-heart"></span>Favorite
    </a>
@endif

Auth::user() works

But, when I try on vue component like this :

<template>
    ...
    <div v-if="Auth::user()">
        <favorite :id="item.id"></favorite>
    </div>
    <a v-else href="javascript:" class="btn btn-block btn-success">
        <span class="fa fa-heart"></span>Favorite
    </a>
    ...
</template>

<script>
    export default {
        props: ...
        computed:{
            ...
        },
        ...
    }
</script>

It does not works

There exist error like this :

invalid expression: v-if="Auth::user()"

How can I use auth on vue component ?

  1. You cannot use Laravel variables (PHP) inside your Vue this way.
  2. You should decide whether you want to build standard app or SPA.
  3. If you want to build standard multipage app, you can place your VueJS components between PHP tags exactly as you do in your first example.
  4. If you still want to build standard multipage app but be able to use your Auth::user() value, there is an option for you in point 5.
  5. Pass value of Auth::user() to the VueJS component as prop.

https://v2.vuejs.org/v2/guide/components.html#Props

Use the prop like that:

props: ['auth'],
(...)
<template>
    ...
    <div v-if="auth">
        <favorite :id="item.id"></favorite>
    </div>
    <a v-if="!auth" class="btn btn-block btn-success"> // avoid using v-else as per VueJS docs
        <span class="fa fa-heart"></span>Favorite
    </a>
    ...
</template>

and use your component in the code like: <favorite :id="{{ $store->id }}" auth="Auth::user()"></favorite>

Not sure if you don't have to cast Auth::user() to string/int but I am pretty sure you will figure it out with php.

您可以使用auth()->user()而不是Auth::user()

I couldn't get the auth user object to work (render without errors) as per accepted answer :(

But I could access and pass through a direct property such as id like so

<example :auth="Auth::user()->id"></example >

Note it has to be "v-bind" because it's a dynamic property and not explicit string.

I also got this to work as another alternative which also produces user ID.

auth="{{ Auth::check() }}"

I'd love to know how to get the object passed into the vue component?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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