Updating a section of a component using another component

I need to update the Header.vue component from the ConfirmCode Component when the confirm method is called

When a user logs in with axios ajax, I want to refresh the li element of the header component

Appointment.vue:

<send-sms-modal@clickClose="setShowModal"
   @clickSend="hideModal"
   @clickConfirm="showStep=true"
   :step="true"
   :showRegister="showRegister"></send-sms-modal>

SendSMSModal.vue:

<confirm-code :mobile="mobileClone"
:user_id="userId" @clickConfirm="clickConfirm" 
:step="step"></confirm-code>
<script>
clickConfirm() {
     this.$emit('clickConfirm');
}
</script>

ConfirmCode.vue:

<button @click="confirm">
      Confirm
</button>
<script>
confirm() {
  axios.post('/api/confirm_code', {
      confirm_code: this.code,
      user_id: this.user_id}).then(function (response) {
        if (response.data.status == true) {
         window.localStorage.setItem('user', response.data.user);
            this.$emit('clickConfirm');
         }}.bind(this)).catch(function (error) {
          this.errors = error.response.data.errors;
       }.bind(this));
}
</script>

Header.vue:

<li>
      <a v-if="user" href="">
             User profile
      </a>
      <a v-else @click="setShowModal"
        href="javascript:void(0)" class="">
         <span>
              Login
        </span>
     </a>
</li>
<script>
mounted() {
   this.user = window.localStorage.getItem('user');
 }
</script>

Answer №1

Consider exploring vuex as a solution.

Vuex allows you to create a centralized store for managing user information globally within your Vue application.

Take a look at the example below:


import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const state = {
  user: window.localStorage.getItem("user")
};

const mutations = {
  SET_USER(state, user) {
    state.user = user;
    window.localStorage.setItem("user", user);
  }
};

const actions = {
  SetUser({ commit }, user) {
    commit("SET_USER", user);
  }
};

const getters = {
  user(state) {
    return state.user;
  }
};

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
});

Utilize the Vuex store in your Vue components like so:

<template>
  <div id="app">
    <h1 v-if="user">Hello {{user}}</h1>
    <button @click="SetUser('John')">Set User</button>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  name: "App",
  methods: {
    ...mapActions(["SetUser"])
  },
  computed: {
    ...mapGetters(["user"])
  }
};
</script>

Ensure to register your Vuex store properly:


import Vue from "vue";
import App from "./App";
import store from "./store";

new Vue({
  el: "#app",
  store,
  components: { App },
  template: "<App/>"
});

For a working example demonstrating the usage of Vuex with localStorage storage, visit: https://codesandbox.io/s/vuex-store-example-39icr?module=%2Fsrc%2Fstore.js

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing a bulk create operation with Sequelize using an array

I am facing a task where I have an array of items that need to be created in the database. My approach is to check each insertion for success. If successful, I will add the item with a flag indicating success as true in a new array (results) in JSON forma ...

Take action upon being added to a collection or being observed

Consider the following scenario: I have an array called "x" and an Observable created from this array (arrObs). There is a button on the page, and when a user clicks on it, a random number is added to the array. The goal is to display the newly added value ...

Issue with tensorflow.js multiple regression stochastic gradient descent optimization

Greetings, everyone! I have recently encountered a perplexing issue while attempting to fit a curve in tensorflow.js. Despite spending a considerable amount of time on it over the past couple of days, I haven't been able to resolve it yet. Given that ...

What is the best way to recreate WordPress categories using static HTML pages?

As I consider converting my WordPress website to static HTML pages, I'm planning on editing them in tools like Responsive Site Designer, Dreamweaver, or SublimeText. My main concern is how I will organize content into categories without the convenien ...

When attempting to trigger an error, the unit test will fail to pass

I am relatively new to Mocha, Chai, and Unit Testing. I'm currently attempting to create a basic test to verify the presence of Authorization headers in the request that passes through my middleware function. Despite trying various approaches such as ...

Exploring Vue 3.1+ and its Delimiters: Common Problems for Beginners

Hi there, I could use a little assistance. I'm just getting started with Vue and I'm having trouble changing the delimiters to get them working properly. Would someone be willing to review this code snippet and let me know if it looks like it sho ...

Combine collapse and popover in Bootstrap 3 for enhanced functionality

I'm facing some issues trying to use the badge separately from the collapse feature. $(function (e) { $('[data-toggle="popover"]').popover({html: true}) }) $('.badge').click($(function (e) { e.stopPropagation(); }) ) Check o ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

In Javascript, swap out a particular colored region in an image with a different image

I've been scouring the internet in search of a solution to my problem, but it seems like I might not be looking in the right places. Imagine this image below, how can I replace the blue area with an image uploaded by the user? I'm struggling to ...

How can I display color without using Winston's color formatter in text?

Currently, I am in the process of developing a logging module using winston as the selected logging framework. It offers the convenience of specifying colors, which is particularly appealing when utilizing the Console transport. However, if I were to defin ...

"jQuery's .each() method is only iterating through the last element in

I am encountering an issue with this function not operating correctly... only the last Element shows the box. NOTES: <aside> is set to position: fixed; and I understand that this is not the "correct" use of <article> tags, but it helps me dist ...

Tips for eliminating Ref upon exiting the screen on React / React Native?

When navigating back in React / React Native, I am encountering keyboard flickering caused by the presence of Ref on the screen. I would like to remove it before leaving the screen. The code snippet I am using is as follows: // To focus on the input fie ...

Terminate the npm build script within a Node.js script

I have developed a node script that checks for the presence of a lock file in my project. If the lock file is not found, I want to stop the npm build process. Any suggestions on how to achieve this? lock-check.js const path = require('path'); c ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

Ways to update a div periodically with new data fetched from a file - Here's How!

I am looking to auto-refresh a specific div every few seconds on my index.php page below. <?php session_start(); if (! check_write()) { redirect('testlogin.php'); return; } if (file_exists('lmt.json')) { $lmt = json_de ...

Utilize AJAX and JavaScript to retrieve file information and facilitate file downloads

I have developed a script that intercepts Captcha form submissions. Typically, when the form is submitted, a file will be downloaded (such as exe or zip) in the usual way where it appears at the bottom of the Chrome browser and gets stored in the "download ...

Exploring Node's Configuration File Reading Process

Trying my best to provide all the details for my question. Being a newbie to NodeJS, I appreciate your kind guidance :D In the process of developing an application in Node, focusing on enabling users to view stats regarding their Plex Media Libraries. The ...

Enhancing Azure B2C User Profiles with Vue and MSAL 2.x

After researching Vue specific examples with MSAL 2.x and opting for the PKCE flow, I have encountered difficulties with the router guards executing before the AuthService handleResponse as expected. It seems like there might be an error in my implementati ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...