简体   繁体   中英

How can I update value in VueJs from api request so that my buttons will be updated without pagereloading or click action or is there another way?

i've tried to solve the problem with putting while(true) inside created so that it will always keep updated by frequently sending requests to flask. Is there another way to update my value?

Vue:

        let app = Vue.createApp({
      data() {
        return {
          session: null,
          showAcc: "",
        };
      },
    
  created() {
    this.fetchLog()
  },

  methods: {
    async fetchLog() {
      let response = await fetch("/logstat");
      if (response.status == 200) {
        let result = await response.json();
        this.session = result;
        if (this.session != null) {
          this.showAcc = "";
        } else {
          this.showAcc = "none";
          setTimeout(this.fetchLog, 500); // repeats the action if nothing comes
        }
      }
    },
    logIn() {
      this.$router.push("/login");
    },
    logOut: async function () {
      console.log("Logging out...");
        let response = await fetch("/logout");
        if (response.status == 200) { 
          this.session=null; 
          this.$router.push("/login");
        }
    },

.... And flask is just a basic session returning response:

    @app.route('/logstat', methods=["GET"])
def logstat():
    '''Checking if user is authorised/session, returning username if so'''
    username = session.get("userid", None)
    return json.dumps(username)

@app.route("/logout")
def logout():
    '''Ending session/logout from account'''
    session.pop("userid", None)
    return 'OK'

And in my index.html

<div v-if=(session) @click='logOut'>
                <p>Logged in as: {{session}} </p> <input type='submit' class='log_info_button pointer' name='submit'
                  value='LOG OUT' /> <i class='fa fa-sign-in' aria-hidden='true'></i>
              </div>
              <div v-else @click='logIn'> <input type='submit' class='log_info_button pointer' name='submit'
                  value='LOG INN' /> <i class='fa fa-sign-in' aria-hidden='true'></i></div>
            </div>

What I'm looking for is a method so that my Login and Logout buttons will update dependently on 'session' status if there is sessionid then logout will appear. if null then login. May be there is another value that can help me instead sessionid?

this.showAcc is for showing 'My account' link in nav bar. It's also dependent oon sessionid.

normally this is caused by use of this keyword in the response/error callback refers to the function itself, and not to the Vue instance; You can resolve it by

  1. Assign the value of this to another variable and use that variable within the callbacks

also try to check login status when instance has been mounted, unless your session expires pretty fast there would be no need to constantly check login status.

    mounted: function(){
      this.checkSession();
    },
    methods:{
      checkSession: async function(){
         let _this = this;
         let response = await fetch("/logstat");
         if (response.status == 200) {
          let result = await response.json();
          _this.session = result;
          _this.showAcc = this.session != null ? "" : "none";
         }
        }
    }

if you need to refresh this information to do it in the backend (or a proxy, for that matter) is definitely not the ideal way to go.

If you need to stop polling the backend once you got the session info, then this is what you can do instead:

  ...
  data: {...},
  created() {
    fetchLog()
  },
  methods: {
    async fetchLog() {
      let response = await fetch("/logstat");
      if (response.status == 200) {
        let result = await response.json();
        this.session = result;
        if (this.session != null) {
          this.showAcc = "";
        } else {
          this.showAcc = "none";
          this.fetchLog(); // repeats the action if nothing comes
        }
      }
    }
  }
  

This would eliminate the need for the timeout on flask.

PS: if you want, you can also put a small timeout for calling this.fetchLog() , like setTimeout(this.fetchLog, 500) for half a second. Ideally, though, you would also have to store this timeout id and with it do a clearTimeout on exit (on unmount or destroy ).

Is very unusual that a website updates current login state without user interaction, anyway whenever I want my server to update my page I use a websocket.

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