sourcecode

VM을 사용할 시기 또는 이 항목을 선택합니다.Vue.js로

copyscript 2022. 7. 26. 23:33
반응형

VM을 사용할 시기 또는 이 항목을 선택합니다.Vue.js로

vue.js에서 "this"라는 단어를 언제 사용해야 할지 잘 모르겠습니다.예를 들어, 아래 코드에서는 "this" 대신 "vm"을 사용하는 경우 코드가 작동하지 않습니다.

"self"를 사용한 예도 몇 가지 보았지만, 저는 Javascript guru가 아니기 때문에 매우 혼란스럽습니다.

var vm = new Vue({
        el: '#app',
        data: {
            tickets: [],
            top: 100,
            search: '',
            showAdd: false,
         },
        mounted: function () {
            this.$nextTick(function () {
                console.log('mounted');
                this.GetTickets(100);
            })
        },
        methods: {
            GetTickets: function (top) {
                axios.get('/api/Tickets', {
                    params: {
                        Top: top
                    }
                })
                    .then(function (response) {
                        vm.tickets = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            ClearTicket: function () {
                var t = {
                    "ticketSubject": '',
                    "contactName": '',
                    "createdAt": moment()
                }
                vm.ticket = t;
                vm.showAdd = !vm.showAdd;
            },
            AddTicket: function () {
                //vm.tickets.unshift(vm.ticket);
                axios.post('/api/Tickets', vm.ticket)
                    .then(function (response) {
                        console.log(response);
                        vm.GetTickets(100);
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
                vm.showAdd = false;

            }
        },

    })

일반적으로 Vue의 내부 메서드 또는 계산된 속성 또는 라이프 사이클 핸들러에서는thisMethod/module/module이 부착된 구성 요소를 참조한다. this는 함수가 현재 실행되고 있는 컨텍스트를 나타냅니다.

를 사용하여 문제가 발생한 경우this새로운 함수가 현재 함수의 컨텍스트에서 선언되는 경우입니다(예: 약속에 콜백을 쓰는 경우).axios.post,axios.get). 다음 코드를 고려합니다.

AddTicket: function () {
  // "this", on this line, refers to the Vue
  // and you can safely use "this" to get any of the
  // data properties of the Vue
    axios.post('/api/Tickets', ...)
      .then(function (response) {
        // "this" HERE, does NOT refer to the Vue!!
        // The reason why explained below              
      })
}

위의 코드에서 첫 번째 코멘트는 다음 코드를 사용하는 코드로 대체될 수 있습니다.thisVue의 데이터 속성 또는 콜 메서드를 가져옵니다(this.tickets단, 두 번째 코멘트는 새로운 기능 컨텍스트 에 있습니다.thisVue를 참조하지 않습니다.이는 Javascript에서 사용자가 새로운 함수를 선언할 때function() {}구문: 해당 함수는 선언된 함수와 다른 자체 함수 컨텍스트를 가집니다.

Javascript에서는 몇 가지 방법이 있습니다.요즘 가장 일반적인 방법은 폐쇄를 사용하여 정확한 정보를 캡처하는 것입니다.this또는 화살표 기능을 사용합니다.다음 코드를 고려하십시오.

AddTicket: function () {
  // As before, "this" here is the Vue
    axios.post('/api/Tickets', ...)
      .then((response) => {
        // "this" HERE is ALSO the Vue
      })
}

이 예에서는 화살표 함수를 사용하여 콜백이 정의됩니다( 참조).() => {}화살표 함수는 자체 함수 컨텍스트를 생성하지 않고 선언된 컨텍스트를 사용합니다.이것은 어휘 범위를 갖는 것으로도 알려져 있습니다.

다른 가장 일반적인 회피책은 폐쇄를 사용하는 것입니다.

AddTicket: function () {
  const self = this // Here we save a reference to the "this" we want
    axios.post('/api/Tickets', ...)
      .then(function(response){
        // and HERE, even though the context has changed, and we can't use
        // "this", we can use the reference we declared (self) which *is*
        // pointing to the Vue
        self.tickets = response
      })
}

마지막으로 바인드 메서드를 사용하여 특정 함수를 생성할 수 있습니다.this그러나 화살표 기능을 사용할 수 있는 요즘에는 일반적이지 않습니다.

AddTicket: function () {
    axios.post('/api/Tickets', ...)
      .then(function(response){
        this.tickets = response
      }.bind(this)) // NOTE the ".bind(this)" added to the end of the function here
}

거의 모든 경우 Vue에 대한 참조를 변수에 저장하는 질문에서 실제로 수행해야 합니다.vmVue 객체 자체 내에서 변수를 사용합니다.그건 나쁜 습관이에요.

어떤 경우에도 올바른 사용 방법this자세한 내용은 인터넷 StackOverflow에 게재되어 있는 다수의 투고에 기재되어 있습니다.

이 입니다.this 올바르게 사용해야 합니다.

var vm = new Vue({
  el: '#app',
  data: {
    tickets: [],
    top: 100,
    search: '',
    showAdd: false,
    ticket: null
  },
  mounted: function () {
    // there is no need for $nextTick here
    this.GetTickets(100)
  },
  methods: {
    GetTickets: function (top) {
      axios.get('/api/Tickets', { params: { Top: top }})
        .then(response => this.tickets = response.data)
        .catch(error => console.log(error));
    },
    ClearTicket: function () {
      var t = {
        "ticketSubject": '',
        "contactName": '',
        "createdAt": moment()
      }
      this.ticket = t;
      this.showAdd = !this.showAdd;
    },
    AddTicket: function () {
      axios.post('/api/Tickets', this.ticket)
        .then(() => this.GetTickets(100))
        .catch(error => console.log(error));

      this.showAdd = false;
    }
  },
})

결국, 그것은 간단하다.이 기능의 구조를 완전히 이해할 수 없을 때까지, 다음의 간단한 룰을 따릅니다.

thisVue 객체의 모든 위치에서 참조 식별자를 외부에 사용합니다.

var vm = new Vue({
  // Use "this" inside
  el: '#app',
  data: {
    something: true
  },
  created: function () {
    this.something = false // like here
  }
})

// Here, outside, use reference iditentifier,
// as you have no other choice
vm.something = null

참조된 개체 자체 내에서 참조 이름을 사용하지 마십시오.Vue 개체 이외에는 참조 이름만 사용해야 합니다.

Vue, Vue 안안this내용은 다를 수 있습니다./오브젝트 으로 생성됩니다.각 함수/개체 내에서 자동으로 생성되는 다른 개체일 뿐입니다. 두 규칙이 합니다.네스트된 두 에 저장하세요. 중첩된 두 번째 레벨 함수로 이동하기 전에 저장this"/" 이유 ""

var vm = new Vue({
  el: '#app',
  data: {
    something: true
  },
  created: function () {
    // You are in first level function,
    // you can use "this"
    axios.get('/uri').then(function () {
      // Here you are in nested, second level
      // function. It will have own "this" object
      this.something = false // no error here but...
      // You did not changed "something" value in data object,
      // you just created new property also called "something",
      // but in this nested "this" object.
    })
  }
})

는 자신의을 갖게 .this this.ar, ,.하면 ' 이라는 속성을 수 있습니다.something = false' 첫 번째 수준 함수의 'this' 개체에서 'this'를 변경하지 않고 중첩된 두 번째 수준 함수의 'this' 개체에 새 속성 'something'을 생성했습니다.의 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아this첫 번째 레벨 함수에서 네스트된 함수를 만드는 과정에서 새로 생성된 콘텐츠로 내용이 덮어쓰기되었습니다.그래서, 만약 당신이 그것을 사용할 필요가 있다면.this중첩된 함수의 객체 양식 첫 번째 수준 함수. 덮어쓰지 않고 다른 이름으로 저장하면 됩니다.

var vm = new Vue({
  el: '#app',
  data: {
    something: true
  },
  created: function () {
    var anyName = this // Save reference to this under another name
    axios.get('/uri').then(function () {
      this.something = false // no error here, but you are still creating new property
      anyName.something = false // NOW you are really changing "something" value in data
    })
  }
})

보시다시피 임의의 이름으로 저장할 수 있습니다..self.것은 아니다.vm이 또 수 에 ''라고을 합니다var vm = new Vue()그렇지 않으면. 않고만 붙이면 됩니다.self.

화살표 기능을 실험하지 않습니다. 바인드를 사용하지 마십시오.이 간단한 규칙을 따르세요.나중에 더 많은 경험을 쌓게 될 것입니다.사용할 수 있습니다(그리고 사용할 필요가 있습니다).단, 지금은 디버깅이 아닌 코딩을 즐겨주세요.

언급URL : https://stackoverflow.com/questions/47148363/when-to-use-vm-or-this-in-vue-js

반응형