user1547174 user1547174 - 1 year ago 124
Javascript Question

How to watch for state/UI changes in vue.js

is there a way I can watch for a state change in the UI?

For example, in my data component I have a variable called

. If the value of
is equal to false, I want my header to display a
link. Likewise, if the value of
is equal to true, I want my header to display a
link. So far I have tried:

<li v-if="loggedIn"><a v-link="{ path: 'login' }" v-on:click="logout()">Logout</a></li>
<li v-else><a v-link="{ path: 'login' }">Login</a></li>

data: function () {

return {
loggedIn: this.isLoggedIn() //this method returns true/false


The code as is has the desired effect. However, it only works if my component is refreshed. I would like
to render accordingly when the value of
changes... Can someone help?

Thanks in advance!

Answer Source

Update I just realized that this.isLoggedIn is a method in your component, and not outside it. It looks like you should make isLoggedIn a computed and use that in your directives.

Yes, you can watch for a state change in the UI, but Vue cannot. Vue does not know that the UI as a whole exists. It only knows about the pieces you tell it about (usually via directives).

In your example code, you initialize loggedIn to the output of a function, but after being initialized, its value is never changed. There is no $watch for things that are outside the ViewModel.

Presumably, there is some login process in which the UI state changes. Since the purpose of the ViewModel is to model the application, you should implement that login process as a method in your ViewModel. Among the things it will do is change the value of the loggedIn variable. As a general rule, UI state should be represented by data members, and anything that changes UI state should be implemented as a method.

It may be that logging in happens up the parent tree from this component. In that case, loggedIn should come in as a prop.