Reputation: 37
Lately I've been trying to use VueJS to create a small project and I have encountered this problem. So I have this navigation bar that includes a Log Out Button element that'd only shown if someone has already logged in. This is my Navbar before I logged in.
Before Login Navbar. No Log Out Button
After I logged in, my navbar'd be like this.
after logged in Navbar. Log Out Button exists
This is my code for this navbar component.
<div id="logout-button" v-if="isLoggedIn">
<button v-on:click="logOut">Log Out</button>
</div>
....
<script>
export default {
name: "NavigationBar",
data: function () {
return {
isLoggedIn: false,
};
},
mounted() {
if (localStorage.isLoggedIn !== undefined) {
this.isLoggedIn = localStorage.isLoggedIn;
}
},
methods: {
...
logOut: function () {
localStorage.isLoggedIn = false;
localStorage.access = null;
localStorage.refresh = null;
location.reload();
},
},
};
</script>
What I've been trying is whenever the log out button clicked, I'd change the value of a key in my local storage, named "isLoggedIn" from "true" to "false". After that, I'd reload the page and when the page reached mounted, the component's data named "isLoggedIn"'d be changed with the new value of my local storage which is now "false". Hence, my expectation is the button wouldnt' be there.
The problem is, whenever I clicked log out, the Log Out Button'd be always there as if I didn't change the value that hopefully doesn't evaluated as "true" in the v-if. I don't know which or what is the problem since I'm new to Vue and I really hope you guys could tell me what it is. Thank you very much!
Upvotes: 1
Views: 420
Reputation: 617
In your logOut()
method, you're only changing the value in the localStorage
, however the v-if="isLoggedin"
is binded to the component's data so you also need to update that.
logOut: function () {
localStorage.isLoggedIn = false;
localStorage.access = null;
localStorage.refresh = null;
this.isLoggedIn = false
location.reload();
},
Additionally, you can only store strings in the localStorage, so you need to evaluate your string to return a boolean for your component's data.
this.isLoggedIn = (localStorage.isLoggedIn === 'true')
Here is a small jsfiddle for you to play with: https://jsfiddle.net/6rv7j5bg/
Upvotes: 1
Reputation: 1705
Try using:
localStorage.setItem("isLoggedIn", false)
and:
localStorage.getItem("isLoggedIn")
and see if it makes any difference!
Upvotes: 1