Al actualizarse la variable userId (de vuex store), necesito que automaticamente se acualizen los links del navbar, es decir, que se vuelva a realizar la condicional de mostrar distintos links. Queria saber si alguno de ustedes conoce alguna forma de escuchar un cambio en dicha variable (de vuex store) para asi poder actualizar los links del navbar.
Este es el appbar. en el cual hago las validaciones con las variables del state para mostrar los links.
<template>
<div>
<v-app-bar
color="deep-purple accent-4"
dense
dark
>
<v-app-bar-nav-icon v-if='showMenu' @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
<v-toolbar-title>Tasks App</v-toolbar-title>
<v-spacer></v-spacer>
<span v-if='!showMenu'>
<v-btn
v-for='(link, i) in links'
:key='i'
rounded
color='transparent'
elevation='0'
:to='link.href'
active-class='white--text text--acent-4'
>
<v-icon>{{ link.icon }}</v-icon>
{{ link.name }}
</v-btn>
</span>
</v-app-bar>
<v-navigation-drawer
v-model="drawer"
absolute
temporary
>
<v-list
nav
dense
rounded
>
<v-list-item v-for='(link, i) in links' :key='i' :to="link.href">
<v-list-item-title>
<v-icon>{{ link.icon }}</v-icon>
{{ link.name }}
</v-list-item-title>
</v-list-item>
</v-list>
</v-navigation-drawer>
</div>
</template>
<script>
export default {
name: "AppBar",
data() {
return {
showMenu: false,
drawer: false,
userId: this.$store.state.userId,
links: !this.$store.state.userId ? [
{ name: "Login", icon: 'person', href: '/' },
{ name: "Signup", icon: 'person_add', href: '/signup' },
] : [
{ name: 'Dashboard', icon: 'dashboard', href: '/dashboard' },
{ name: "Cerrar sesion", icon: 'exit_to_app', href: '/close_session' },
]
}
},
methods: {
menuValidator() {
this.showMenu = window.innerWidth <= 580
},
menuListeners() {
window.addEventListener('resize', this.menuValidator)
window.addEventListener('load', this.menuValidator);
}
},
mounted() {
this.menuListeners();
},
watch: {
userId: function() {
// Aqui deseo que se actualize el sidebar, pero por desgracia el siguiente console.log no se ejecuta al loguearme
console.log('ok')
}
}
}
</script>
<style scoped>
*.v-btn.v-btn--router {
color: white !important;
}
</style>
Aqui el login. Que solamente llama al componente LoginForm (formulario), y LoginTitle (titulo del login).
<template>
<div>
<LoginTitle />
<LoginForm />
</div>
</template>
<script>
import LoginTitle from '@/components/LoginTitle'
import LoginForm from '@/components/LoginForm'
export default {
name: "Login",
components: {
LoginTitle,
LoginForm,
}
}
</script>
Aqui el componente LoginForm. En el cual creo el formulario de login, y actualizo tambien las variables del store.
<template>
<v-row>
<v-col
cols='12'
sm='0'
md='3'
/>
<v-col
cols='12'
sm='12'
md='6'
>
<v-card
elevation='2'
shaped
:loading="loading"
class='mx-auto ml-12 mr-12'
>
<v-card-text>
<form>
<v-row no-gutters>
<v-col
cols="12"
sm="12"
v-if="error !== ''"
>
<v-alert
color="red"
type="error"
elevation="5"
border="left"
>
{{ error }}
</v-alert>
</v-col>
<v-col
cols='12'
sm='12'
>
<v-text-field
type='text'
v-model='name'
label='Nombre'
color="deep-purple"
required
@keyup.enter="onSubmit"
/>
</v-col>
<v-col
cols='12'
sm='12'
>
<v-text-field
type='password'
v-model='password'
label='Contraseña'
color="deep-purple"
required
@keyup.enter="onSubmit"
/>
</v-col>
<v-col
cols="12"
sm="12"
>
<v-btn
block
@click="onSubmit"
color="deep-purple accent-3"
dark
>
Empezar
</v-btn>
</v-col>
</v-row>
</form>
</v-card-text>
</v-card>
</v-col>
<v-col
cols='12'
sm='0'
md='3'
/>
</v-row>
</template>
<script>
import { sleep } from "../util";
import { findUser } from "../requests/findUser";
import { login } from "../requests/login";
import { errorsValidations } from "../requests/helpers";
export default {
name: "LoginForm",
methods: {
/**
* Show a error and delete it
* @param msg
* @returns {void}
*/
async showError(msg) {
this.loading = false;
this.name = '';
this.password = '';
this.error = msg;
await sleep({ ms: 2000 });
this.error = '';
},
/**
* Realize the login function
* @param {any} res The user response
* @returns {Promise<void>}
*/
async login(res) {
this.loading = false;
localStorage.setItem('_', res.data.login._id);
this.$store.commit('setUser', res.data.login);
await this.$router.push('/dashboard');
},
/**
* Execute in onSubmit event
* @returns {Promise<void>}
*/
async onSubmit() {
this.loading = true;
const res = await login({ name: this.name, password: this.password });
await errorsValidations({ requestResponse: res, showErrorFunction: this.showError });
await this.login(res);
}
},
async mounted() {
const { userId } = this.$store.state;
if (userId) {
// User is logged
// Realizing the fetch to obtain the logged user
// by the store saved _id
this.loading = true;
const user = await findUser({ _id: userId });
await errorsValidations({ requestResponse: user, showErrorFunction: this.showError });
await this.login({ data: { login: { ...user.data.findUser } } });
}
},
data() {
return {
error: "",
loading: false,
name: "",
password: "",
}
}
}
</script>
Y Aqui el App.vue. En el cual defino las funciones para actualizar el usuario si esta logueado y ademas valido las consultas (si todo va bien).
<template>
<v-app>
<AppBar />
<ErrorSnackBar
:error="error.open"
:text="error.text"
:timeout="error.timeout"
/>
<v-container>
<router-view></router-view>
</v-container>
</v-app>
</template>
<script>
import AppBar from '@/components/AppBar'
import ErrorSnackBar from "./components/ErrorSnackBar";
import { findUser } from "./requests/findUser";
import { errorsValidations } from "./requests/helpers";
export default {
name: "App",
components: {
AppBar,
ErrorSnackBar,
},
data() {
return {
error: {
open: false,
text: '',
timeout: 2000,
}
}
},
methods: {
/**
* Show a error
* @param {string} text Text to show
* @returns {void}
*/
showError(text) {
this.error = {
error: true,
text: text,
timeout: 2000, // 2 seconds...
}
}
},
async mounted() {
const { userId } = this.$store.state;
if (userId) {
// Is logged saving user
const user = await findUser({ _id: userId });
await errorsValidations({ requestResponse: user, showErrorFunction: this.showError });
this.$store.commit('setUser', user.data.findUser);
}
}
}
</script>
Aqui el componente ErrorSnackBar. el cual simplemente muestra un snackbar en pantalla a traves de los componentes de vuetify.
<template>
<v-snackbar
v-model="error"
:timeout="timeout"
>
{{ text }}
<template v-slot:action="{ attrs }">
<v-btn
color="deep-purple"
text
v-bind="attrs"
@click="error = false"
>
Cerrar
</v-btn>
</template>
</v-snackbar>
</template>
<script>
export default {
name: "ErrorSnackBar",
props: ['error', 'timeout', 'text']
}
</script>
y aqui esta el src/store/index.js en el cual defino todas las variables de vuex store. y ademas algunas mutaciones que me permiten alterar las variables del state.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
user: {},
userId: localStorage.getItem('_') || '',
},
mutations: {
setUser(state, newUser) {
state.user = newUser;
state.userId = newUser._id;
}
},
actions: {
},
modules: {
}
})