简体   繁体   English

如何从 api 请求更新 VueJs 中的值,以便在不重新加载页面或单击操作的情况下更新我的按钮,还是有其他方法?

[英]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.我试图通过将 while(true) 放入 created 来解决问题,以便通过频繁向 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: .... flask 只是一个基本的 session 返回响应:

    @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在我的索引中。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.我正在寻找的是一种方法,以便我的登录和注销按钮将根据“会话”状态进行更新,如果有 sessionid 则将出现注销。 if null then login.如果 null 然后登录。 May be there is another value that can help me instead sessionid?可能有另一个值可以帮助我而不是 sessionid?

this.showAcc is for showing 'My account' link in nav bar. this.showAcc用于在导航栏中显示“我的帐户”链接。 It's also dependent oon sessionid.它也依赖于 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;通常这是由于在响应/错误回调中使用this关键字导致的,是指 function 本身,而不是 Vue 实例; You can resolve it by您可以通过以下方式解决

  1. Assign the value of this to another variable and use that variable within the callbacksthis的值分配给另一个变量并在回调中使用该变量

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.还尝试在安装实例时检查登录状态,除非您的 session 很快过期,否则无需经常检查登录状态。

    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.如果您需要在后端(或代理,就此而言)刷新此信息绝对不是 go 的理想方式。

If you need to stop polling the backend once you got the session info, then this is what you can do instead:如果您在获得 session 信息后需要停止轮询后端,那么您可以这样做:

  ...
  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.这将消除 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. PS:如果你愿意,你也可以设置一个小的超时来调用this.fetchLog() ,比如setTimeout(this.fetchLog, 500)半秒。 Ideally, though, you would also have to store this timeout id and with it do a clearTimeout on exit (on unmount or destroy ).但是,理想情况下,您还必须存储此超时 ID,并在退出时(在unmountdestroy时)执行clearTimeout

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.网站在没有用户交互的情况下更新当前登录 state 是非常不寻常的,无论如何,每当我希望我的服务器更新我的页面时,我都会使用 websocket。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何保存“图像点击”值,以便我可以继续在我的 PHP 程序中使用该值? - How can I save an "Image Click" value so that I can continue working with this value in my PHP program? 所以我想从我的代码中提取这些按钮的值我应该怎么做 - So i want to extract the value of these buttons from my code how should i do it 如何获得我的API请求以获取更新的数据库? - How do I get my API request to grab the updated Database? 如何定期更新VueJS中的组件 - How can I periodically update my component in VueJS 如何转换此js代码,以便通过输入值和单选按钮值更新对象的每个属性? - How can I transform my this js code so that every property of an object get updated by an input value and radio button value? 如何从带有 2 个按钮的表单单击按钮时发送 Ajax 请求? - How can I send an Ajax Request on button click from a form with 2 buttons? 如何更新数据库中的所有行并显示更新的数据而无需刷新? - How can I update all row from database and show updated data without refresh? 如何捕获我单击的项目,以便将其传递给 API - VueJS &amp; Quasar - How can I capture the item that I clicked on so I can pass it to the API - VueJS & Quasar 如何使用更新的上下文数据更新从 api 获取的数据? - How can I update the data taken from the api using the updated context data? 如何在使用更新的依赖值调度操作后更新 api 调用 - How to an update an api call after an action is dispatched with a dependant value which is updated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM