何时使用vm。或这个。在Vue.js [英] When to Use vm. or this. in Vue.js

查看:111
本文介绍了何时使用vm。或这个。在Vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对何时在vue.js中使用this这个词感到有点困惑。例如,在下面的代码中我使用vm而不是this代码不起作用。

I am a little confused on when to use the "this" word in vue.js. For example, in the code below everywhere I use "vm" instead of "this" the code does not work.

我也看过一些使用self的例子,但是我不是一个javascript大师,这真的令人困惑。

I have also seen some examples using "self", however I am not a javascript guru and this is really confusing.

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;

            }
        },

    })


推荐答案

我通常会将这个问题标记为重复,但是,由于对这个<的整体混淆,我觉得这个具体问题需要多一点解释。 / code>一般来说,以及它应该如何在Vue中使用。

I would typically mark this question as a duplicate, however, I feel this specific question merited a little more explanation because of the overall confusion about this in general, and how it should be used in Vue specifically.

通常,在Vue中的内部方法,计算属性或生命周期处理程序中,您将使用 this 来引用方法/ computed / handler附加到的组件。 指的是当前正在执行该函数的上下文。

Typically, inside methods, or computed properties or lifecycle handlers in Vue, you will use this to refer the component to which the method/computed/handler is attached. this refers to the context in which the function is currently executing.

使用<$ c遇到麻烦的地方$ c>这个是在当前函数的上下文中声明一个新函数的时候,就像你写一个回应到一个promise( axios.post axios.get )。考虑以下代码:

Where you get into trouble using this is when a new function is declared in the context of the current function, as happens when you write a callback to a promise (axios.post, axios.get). Consider this code:

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              
      })
}

在上面的代码中,第一条评论可以替换为使用<$的代码c $ c> this 获取数据属性或调用Vue的方法( this.tickets )。然而,第二条评论是里面一个新的函数上下文,而这个将不会引用Vue。这是因为在Javascript中使用 function(){} 语法声明一个新函数时,该函数有自己的函数上下文不同来自声明它的函数。

In the above code, the first comment could be replaced with code that uses this to get data properties or call methods of the Vue (this.tickets). The second comment, however is inside a new function context, and this will NOT refer to the Vue. This is because in Javascript when you declare a new function using the function() {} syntax, that function has its own function context which is different from the function in which it is declared.

在Javascript中有几种方法可以解决这个问题。这些天最常见的是要么使用闭包来捕获正确的这个,要么使用箭头函数。考虑以下代码:

There are several ways to deal with this in Javascript. The most common these days are to either use a closure to capture the correct this, or to use an arrow function. Consider this code:

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

请注意,在此示例中,使用箭头定义回调功能(()=> {} )。箭头函数不会创建自己的函数上下文并使用声明它们的上下文。这也被称为具有词法范围。

Note that in this example, the callback is defined using an arrow function (() => {}). Arrow functions do NOT create their own function context and use the context in which they are declared. This is also known as having a lexical scope.

其他最常见的解决方法是使用闭包。

The other most common workaround is using a closure.

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
      })
}

最后,您可以使用 bind方法创建一个具有特定 this 的函数,尽管这不是这些天可以使用箭头功能。

Finally, you can use the bind method to create a function with a specific this, though this is not as common these days with arrow functions available.

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
}

几乎不会,你真的应该做你做的事吗在您的问题中,这是在变量 vm 中保存对Vue的引用,并在Vue对象本身内使用该变量 。这是一个不好的做法。

In almost no case, should you really be doing what you do in your question, which is save a reference to the Vue in the variable vm and use that variable inside the Vue object itself. That's a bad practice.

在任何情况下,如何使用正确的这个都会在很多帖子中详细介绍整个互联网还有StackOverflow

In any case, how to use the correct this is covered in detail in numerous posts throughout the internet and here on StackOverflow as well.

最后,这里是修订问题的代码,这样这个 应该正确使用。

Finally, here is the code from the question revised such that this should be used correctly.

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;
    }
  },
})

这篇关于何时使用vm。或这个。在Vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆