简体   繁体   中英

How to get data from server before component is mounted vue2.0

I've got a question like in the title
How to stop mounting the component in <router-view> until receive a data from server or how to get the data before the component is mounted to <router-view>

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 to do it properly to get not null value, but response from the server?
Thank you in advance

resolved with:

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

and in 2nd file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM