用ajax请求数据无法后无法更新视图怎么解决,控制台的数据改变了但是视图没有改变

请输入代码<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Document</title>
  <link rel="stylesheet" type="text/css" href="./css/login.css"/>
  <script type="text/javascript" src="./js/vue.js"></script>
  <script type="text/javascript" src="./js/axios.min.js"></script>
</head>
<body>
  <div id="app">
    <div id="login" v-show="!onOff">
      <div id="login_box">
        <h3>登陆</h3>
          <input type="text" name="username" autocomplete="off" placeholder="username" v-model="username"/>
          <input type="password" name="password" autocomplete="off" placeholder="password" v-model="password"/>
          <input type="submit" value="提交" v-on:click="getIn"/>
        
      </div>
      
    </div>
    <div id="content" v-show="onOff">
      
    </div>
  </div>

</body>
<script>

var vm=new Vue({
  el:'#app',
  data:{
    username:'',
    password:'',
    onOff:false,
  },
  methods:{
    
    getIn:function(){

      axios.get('/login',{
        params:{
          user:this.username,
          pass:this.password,
        }
        }).then(function(res){
          this.onOff=res.data.ok
          console.log(res.data.ok)
        }).catch(function(err){
        console.log(err)
      })

    },


  }

})

</script>
</html>

图片描述

阅读 3.2k
1 个回答

this指向的问题,在回调函数中,this指向的是回调函数。
办法一:用变量that指向this

    var that =this
    ...
    then(function(res){
       that.onOff = res.data.OK
    })
    

方法二:用箭头函数,箭头函数不会改变this的指向

    then(res=>{
       that.onOff = res.data.OK
    })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题