Gazoo
2640
5
Vue

Using v-if to render one template or another based on a props

Posted 1 year ago by Gazoo

Hey lovely people,

I'm slowly easing myself into understanding and using Vue with Laravel as it's an integral part of the straightforward tutorial on how to build a simple chat app which I've implemented.

It all works great and I'm happy. Then I decide to change the application a bit to also allow unauthorized users to see, but not send any chat messages, and here's where things go sideways.

The first issue with this new feature is in the blade file containing this bit of code:

                <div class="panel-footer">
                    <chat-form
                        v-on:messagesent="addMessage"
                        :user="{{ Auth::user() }}"
                    ></chat-form>
                </div>

If this allowed to run without a user logged in, Auth::user() evaluates to nothing, and the JS engine throws a fit because there's now code that says user: }in the JS which it, understandably, dislikes.

After a bit of reading, understanding, and thinking, I manage to come up with this alternative

                <div class="panel-footer">
                    <chat-form
                        v-on:messagesent="addMessage"
                        :user="{{ Auth::user() ? Auth::user() : 'false' }}"
                    ></chat-form>
                </div>

I'm not sure it's the smartest solution, but works for now - I'm all ears to an improvement. The problem I'm now facing is that I'd like for the template that the tutorial provides to change based on whether or not the user is actually logged in or not. But I cannot for the life of me get the v-if statement to behave the way I'd like it to. The vue file currently looks something like this:

<template v-if="user !== false">
    ... chat html WITH a send button ...
</template>
<template v-else>
    ... chat html WITHOUT a send button ...
</template>

<script>
    export default {
        props: ['user'],

    ... other stuff ...
    }
</script>

But the v-if will always evaluate to false. I'm not sure if perhaps directly accessing props in the template is bad, but according to what I've read it should be possible. I've tried variations (ala v-if="user" and more) but nothing has worked. Using the chrome Vue extension I can see that user is being set to false (or perhaps the string of false) or the user object (or perhaps the user json string), but I'm struggling to understand how to properly branch on the input in Vue.

Any suggestions on how to render one template or another based on the passed user data?

Thanks in advance,

Gazoo

Please sign in or create an account to participate in this conversation.