Vue中this的指向問題

在Vue中通常會用this去調用在Vue原型上的方法。

handleSubmit2(ev) {
        var _this = this;
        this.$refs.ruleForm2.validate((valid) => {
          if (valid) {
            //_this.$router.replace('/table');
            this.logining = true;
            //NProgress.start();
            var loginParams = { username: this.ruleForm2.account, password: this.ruleForm2.checkPass };
            requestLogin(loginParams).then(data => {
              this.logining = false;
              //NProgress.done();
              let { msg, code, user } = data;
              if (code !== 200) {
                this.$message({
                  message: msg,
                  type: 'error'
                });
              } else {
                sessionStorage.setItem('user', JSON.stringify(user));
                this.$router.push({ path: '/table' });
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }

我在函數體內寫了一個this.$router.push(’/table’)方法,其主要目的是爲了在驗證完成後進行路由跳轉,跳轉到table頁面。 當運行過後會報個錯。 其報錯原因是因爲在函數內部this的指向出現了問題。可以在函數體外把this賦值給變量。然後再函數內部再進行調用 我在函數體外對this進行重新賦值,就可以解決這個問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章