IT이야기

정의되지 않은 속성 '$router'를 읽을 수 없음

cyworld 2022. 3. 19. 12:03
반응형

정의되지 않은 속성 '$router'를 읽을 수 없음

주어진 코드에 문제가 있어서

submit () {
    fetch(this.url + "/auth/login",{
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        mobilenumber: this.form.mobilenumber,
        password: this.form.password})
    }).then(function (response) {
      console.log("Response = " + response.status);
      if (response.status == 200) {
          this.$router.push({
             name: "Users",
          })
      } else {
          alert("Not logged in");
      }
      return response.json();
    }).then(function (data) {
      
    }).catch(function (error) {
      console.log("-------- error ------- " + error);  
    });
}

제출 기능이 호출되면 Users 페이지로 이동하십시오.나는 썼다.this.$router.push({ name: "Users" })그것을 위해서그러나 콘솔에서 오류가 발생하는 경우:

Cannot read property '$router' of undefined.

나는 노력했다.self.$router.push({ name: "Users" })아직도 나는 콘솔에서 같은 실수를 하고 있다.도와줘.

외부 범위에 대한 참조가 필요한 이유는 가져오기 콜백에서this정의되지 않았다.이 문제를 해결하려면 다음과 같이 참조를 생성하여 외부 범위의 참조를 만들 수 있다.

submit () {
    let self = this;
    ...

그러면 참조를 다음과 같이 사용할 수 있다.

self.$router.push({
    name: "Users",
})

참조URL: https://stackoverflow.com/questions/63943017/cannot-read-property-router-of-undefined

반응형