0

how to make v-if when rendering to another component to render fast ? i have some case , when i am going to login and after success my nabvar component doest change after it finished, i should manually reload it on my client to get logout button and it is same also when i delete , i should manually to reload tho i already put :key on that component

here is my component in my login.vue page

goLogin() {
    if (!this.input || !this.password) {
      this.$swal.fire({
        type: 'error',
        text: `please enter your email/username and password`,
      });
    } else {
      const client = {
        input: this.input,
        password: this.password,
      };
      this.$axios
        .post('/api/user/login', client)
        .then(({
          data
        }) => {
          localStorage.setItem('token', data.token);
          // vm.$forceUpdate();
          localStorage.setItem('role', data.tryingLogin.role);
          this.$swal.fire({
            type: 'success',
            text: `successfully login`,
          });
          if (data.tryingLogin.role === 'admin') {
            this.$router.replace({
              path: '/admin'
            });
          } else {
            this.$router.push({
              path: '/'
            });
          }
        })
        .catch(err => {
          this.$swal.fire({
            type: 'error',
            text: err.response.data.error,
          });
        });
    }

and on my Header.vue component, i have isLogin props, and i check by if localStorage.getItem("token") i close the button login and register on navbar header.vue and it should show logout button if client has token, but it was not, after succesfuly login, i should reload it to get the button logout showing

how to force it to be changed quickly ? to swap show and hide button login and logout ??

i also make props to check login on my App.vue and i use all hooks lifecyly to swap login button ans logout , it doesnt changed at all, :(

and it happends when i delete my list also, i should reload it :( i hope you guys could give me some help and trick for solve this problem :D

1 Answer 1

2

To share state between different components your best choice would be to use a state management library like Vuex: https://vuex.vuejs.org

You create a store which holds information on whether the user is logged in or not:

const store = new Vuex.Store({
  state: {
    isLoggedIn: false
  },
  mutations: {
    TOGGLE_LOGIN_STATUS: (state) => {
      state.isLoggedIn = !state.isLoggedIn;
    }
  }
})

When you successfully log in, you change the isLoggedIn flag:

store.commit('TOGGLE_LOGIN_STATUS');

And you can fetch this status from the store in any of your components (it's also reactive, so changes reflect in all of your components) - it has to be a computed property:

computed: {
  isLoggedIn() { return store.state.isLoggedIn; },
}

You can now use isLoggedIn in your v-if to display a logout button. Just remember to either import your store in your components or make it global (everything you need is in the Vuex's docs).

Another way is using an event bus.

/src/event-bus.js

import Vue from 'vue';
export const EventBus = new Vue();

Import it in your Login component.

import EventBus from '@/event-bus';

After getting the token and successfully logging in, emit an event:

EventBus.$emit('logged-in', true);

Now import EventBus in a component that's receiving the event (your component with logout button) and place a listener in your mounted hook:

mounted() {
  EventBus.$on('logged-in', payload => {
    this.isLoggedIn = payload;
  })
}
Sign up to request clarification or add additional context in comments.

7 Comments

for my project, i should not using Vuex yet, do u have any method with Vue only and without Vuex ?? :D
Yes, you could also create an event bus. I've updated my answer.
hmm i will try and be back soon, so the event bus is like a store state ? is that right ??
oh ya, the mounted hook is in my header navbar component ? or App.vue ??
Not really; you use it to emit events inside of your app. Each event has got a name (of your choice) and you can optionally pass a payload (value) together with it. Another component can subscribe (listen to) this particular event (by it's name) and perform certain actions when it's emmited. The mounted hook can be used in all of your components, but in this scenario, you should register the listener in the component where your Logout button is (or your isLogin prop - your Header.vue if I'm correct);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.