John Moore
John Moore

Reputation: 7129

Reactive properties issue with vue.js

I have run into a baffling issue with reactive properties in a Vue.js app, which probably results from a misunderstanding on my part and I hope someone can help. In my App.vue, I have import auth from 'src/auth.js', and in my data properties I have this:

 data() {
  return {
    authenticated: auth.user.authenticated,
    role: auth.user.role
  }
 },

This authenticated property is used to show or hide various menu items, e.g:

<li v-if="!authenticated">
  <router-link to="/login">Log In</router-link>
</li>
<li v-if="authenticated"><a href="#" @click.prevent="logout">Log Out</a></li>

What I'm finding is that changes to 'auth.user.authenticated' (e.g., switching from false to true after a successful login) are not being reflected in the rendering of the menu items - that is, the authenticated data property is not being updated. To do so, I have to explicitly update it in 'beforeUpdate' and the logout method, with this.authenticated=auth.user.authenticated. At first I thought it was simply that this was assigned on first creation and not subsequently updated and that if I used a computed property instead, this would be dynamic, but that doesn't do the job either. Clearly my App component is unaware of changes to the 'auth' data. How can I make things so that updating is automatic? I have it working at present but the use of 'beforeUpdate' feels like a kludge.

Upvotes: 0

Views: 198

Answers (1)

Roy J
Roy J

Reputation: 43881

Vue data items are reactive, but non-Vue data items are not reactive. Your code initializes a reactive data item with the value from a non-reactive one.

There is no way for Vue to watch external (to Vue) variables for changes. You will need to notice when your variable changes and tell Vue about it, or just use the external variable (instead of an internal copy) when you need it.

Upvotes: 1

Related Questions