3👍
The created
is a lifecycle or hook of vue.js, inside it whatever functions/methods you define, is not available to run.
As in your case, you want to use as a variable, then use computed
property.
Here is the fix version of your code:
computed: {
isLoggedIn() {
console.log(JSON.parse(localStorage.getItem("loggedIn")) === "true");
if (localStorage.getItem("loggedIn") === "true") {
console.log("STORAGE LOGGED IN TRUE");
}
else {
console.log("STORAGE LOGGED IN FALSE");
}
return localStorage.getItem("loggedIn") === "true";
}
},
Updated:
If you want your functions to be reactive on the same component, then create a variable and set its value where you set the localStorage loggedIn value.
This is just an example code:
<template>
<div class="flex flex-wrap items-center justify-end ">
<h3>{{ isLoggedIn }}</h3>
</div>
</template>
<script>
export default {
data () {
return {
loggedIn: false
}
},
created () {
// added 3 seconds gap to make the value true and check reactivity
setTimeout(() => this.onSignIn(), 3000)
},
computed: {
isLoggedIn() {
if (localStorage.getItem('loggedIn')) return localStorage.getItem("loggedIn") === "true";
return this.loggedIn
}
},
methods: {
onSignIn () {
this.loggedIn = true
localStorage.setItem('loggedIn', true)
}
}
}
</script>
Update 2 as per your situation:
After understanding your situation, here is the code, that will help you. I used the Bus Event in order to communicate between the component which might be far on the parent to access, such as App.vue.
event-bus.js
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;
LoginForm.vue
<template>
<div class="home-page">
<button type="submit" @click="onSignIn()">Login</button>
</div>
</template>
<script>
import EventBus from '../event-bus';
export default {
methods: {
onSignIn () {
localStorage.setItem('loggedIn', true)
EventBus.$emit('OnLogin', true)
}
}
}
</script>
App.vue
<template>
<div id="app">
<Header :userLoggedIn="isLoggedIn"/>
<router-view/>
</div>
</template>
<script>
import Header from './components/Header'
import EventBus from './event-bus';
export default {
components: {
Header
},
data() {
return {
isLoggedIn: false
}
},
created () {
EventBus.$on('OnLogin', (isLogin) => {
this.isLoggedIn = isLogin
})
}
}
</script>
Header.vue
<template>
<div>
<h2>{{ userLoggedIn }}</h2>
</div>
</template>
<script>
export default {
props: ['userLoggedIn']
}
</script>
- [Vuejs]-404 Cannot find "/dist/vue-router.js" in vue-router@4.0.15
- [Vuejs]-KeyError at / 'assets' and ModuleNotFoundError: No module named 'webpack_loader'
Source:stackexchange.com