How can we fetch data from the server in Vue 2.0 before the component is actually mounted?

Can anyone help me with this question noted in the title? How can I prevent a component from mounting in <router-view> until it receives data from the server, or how can I fetch the data before the component is mounted in <router-view>?

Here are my files:

1st main.js

new Vue({
  el: '#app',
  router,
  components: { Login, Start },
  data: function(){
    return{
      info: null,
    }
  },
  methods:{
    bef:function(){
      this.$http.get('xxx').then(function(response){
        return response.body
      });
    }
  },
  beforeMount(){
    this.info = this.bef()
  }
})

2nd component file Comp.vue

export default {
    name: 'start',
    data(){
        return{

        }
    },
    beforeMount(){
       console.log(this.$parent.info)
    }
}

How can I properly ensure that I get a non-null value, but rather a response from the server?
Thank you for your help.

Answer №1

Solved using the following method:

verifyLoginStatus: function() {
        return new Promise((resolve,reject) => {
          this.$http.get('xxx').then(response => {
            if (response.body == 1) {
              resolve(true);
            } else {
              resolve(false);
            }
          }, response => {
            reject('connection issue');
          });
        });
    },

Then, in a separate file:

this.$root.verifyLoginStatus().then((response) => {
            if(response){
                this.logged = true
            }else{
                router.push("/")
            }
        })

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

Monitor the change in FileReader().readyState using AngularJS

Below is the AngularJS code I have written to read a local file. var files = document.getElementById("file"); files.addEventListener("change", handleFile, false); function handleFile(event) { SpinnerService.upload(); // Display loading spinner ...

Flat list in React Native is not showing any items on the screen

Just checking in to see how you're doing I'm facing a strange issue with my react-native project. The FlatList items on some pages are not being displayed, even though I can see them when I console.log(json.items). Earlier today, everything was ...

How can you stop vue.js from triggering data re-renders?

My Vue component features a prop named data, receiving the initial 25 results from a backend query. The plan is to later fetch approximately 250 results, with the additional results fetched using an AJAX call and an offset of 25. This approach allows user ...

Make a JSONP request with the MIME Type set to text/plain

I've been attempting to utilize JSONP for fetching a feed from a different domain. Despite knowing that the content type should ideally be JSON or JavaScript, it is currently set as text/plain and unfortunately, I lack control over the server settings ...

Incorporate an interface for handling potential null values using Typescript

Currently, I am utilizing Express, Typescript, and the MongoDB Node.js driver to develop my API. However, I am encountering an issue with the findOne method as it returns a promise that resolves with either an object containing the first document matching ...

Using Node.js to update information within Firebase

Here's a problem I'm facing: I have a cron job running in Node.js that sends data to a Firebase database every minute. The issue is, even when there are no changes, the database still receives information. Take a look at my code snippet below: l ...

How to set the default value for an angularJS select dropdown

Can someone assist me with setting a default value for a select dropdown using AngularJS? I have explored similar threads on StackOverflow, but none of the suggested solutions have resolved my issue. Therefore, I am reaching out to seek help here. Essenti ...

Open Modal in Vue-Router Using Code

My current setup involves a login page that redirects users to it if they are not authenticated (verified via the meta tag auth). On the other hand, if a user is already logged in and tries to visit the login page, they are redirected to the home page (det ...

Alphabetic divider for organizing lists in Ionic

I am currently working with a list in ionic that is fetched from a controller and stored in localStorage. My goal is to add alphabetic dividers to the list, but I am facing some confusion on how to achieve this. Here is a snippet of the code: app.js $ion ...

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

Retrieve a DOCX file via AJAX response

I am encountering an issue with a Django function that returns a file: ... return FileResponse(open('demo.docx', 'rb')) I am using ajax to fetch it on the client side. Now, I need to download it on the client side. This is the code I a ...

Testing the capabilities of AngularJS with e2e testing using the angular-recaptcha library

I have been attempting to e2e test my basic application, but I am facing challenges with the angular-recaptcha plugin from VividCortex (https://github.com/VividCortex/angular-recaptcha). Here is the test case I am working on: it('should redirect t ...

Verify the completeness of data types within an array in typescript

I am currently developing a comprehensive match function that I want to ensure is exhaustive during compile time. Although adding a default case would help with this, I am intrigued by some interesting dependent typing techniques I have come across. It wou ...

Obtain data from files within a React frontend application

I have integrated an API endpoint into my NodeJS application. The purpose of this endpoint is to locate a specific file in a folder based on the filename provided in the request. Here's how I am approaching this: const fileDirectory = 'C:/Sites/p ...

Dealing with empty POST request bodies in Node.js Express is a common challenge

In my Node.JS project using Express framework, I am encountering an issue while trying to access the body of a POST request. The POST request is being sent through an HTML form, and upon checking with WireShark, I can see that the request is indeed getting ...

Simulated web server for testing with Jest

Can I ask a unique question? I have a tool for extracting data from webpages directly, not through APIs. I want to create end-to-end tests for this tool using the Jest library, but I need to ensure the web pages I'm referencing remain consistent. It&a ...

Guide on navigating to a different page following a successful Google Sign In within React18

I'm facing an issue with redirection after signing in with Google on my React 18 project. Despite successfully logging in, the page does not redirect as expected. Below is a snippet of my Login.jsx file where the Google login functionality is implemen ...

View a specific selected newsAPI article on its own dedicated page

I have been working on a news website and successfully displayed all the articles on a single page using the news API in nodeJs. Everything is functioning well, but now I want to show the clicked article on a separate page. Although I managed to route it t ...

Is there a way to first run my validate function and then proceed with sending my AJAX request upon clicking a button?

Hey there! I've got a dynamic table generated from a database. You can check out the table. I have all the necessary code in place, but what I really need is to ensure proper timing of execution for specific actions: 1) Verify if all mandatory fields ...