繁体   English   中英

如何修复 VueJS 中的“这是未定义的”?

[英]How can i fix “this is undefined” in VueJS?

this.$store.commit('disconnect'); 导致“这是未定义”错误,我该怎么办?

存储/index.js:

export const state = () => ({
  log: false,
  user: {token: null, id: null, username: null, email: null, created_at: null, pseudo: null}
})


export const mutations = {
  connect (state) {
    state.log = true
  },
  disconnect (state) {
    state.log = false,
    state.user.id = null,
    state.user.username = null,
    state.user.email = null,
    state.user.created_at = null,
    state.user.pseudo = null
  }
}

索引.vue

<script>
import axios from "axios";

  methods: {
    async login() {
    var self = this;

    const auth_res = axios({
      method:'post',
      url:'http://127.0.0.1:8000/v2.0/auth',
      data:{
        username: this.username,
        password: this.password
      }
      }).then(function(res){
        this.$store.commit('disconnect');
        self.$router.push('/');
      }).catch(function (erreur) {
        console.log(erreur);
      });
    }
  }
}
</script>

如果我删除index.vue文件中的commit行,它工作正常,但我需要使用它,那么我该如何解决这个问题?

再次感谢

在回调上下文中, this时态回调本身。 这就是您收到错误的原因。 您应该将其替换为,

self.$store.commit('disconnect');

self持有 Vue 的实际上下文。 这里是解释,

methods: {
    async login() {
    var self = this; // You got the context of the method which belongs to Vue

    const auth_res = axios({
      method:'post',
      ...
      }).then(function(res){
        self.$store.commit('disconnect'); // The self.$store is now avaialable in callback
        self.$router.push('/');
      }).catch(function (erreur) {
        ...
      });
    }
  }

暂无
暂无

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

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