A
A
AL_32018-04-04 12:12:56
JavaScript
AL_3, 2018-04-04 12:12:56

Why is the variable from the second anonymous function not visible?

Hi all.
I use vue.js, there is this piece of code:

props: ['user'],

        computed: {
            incomingActive: function () {
                let user_name = this.user;
                this.messages.forEach(function (message) {
                    alert('user_name is: ' + user_name);   // <-- обращение к переменной здесь
                  /* ... */
                    return incomingActive;
                });
            }
        },

I want to access the variable props: ['user'], I write this.user and user, but errors [Vue warn] fly out: Error in render: "TypeError: this is undefined" and user is not defined, I have to create an intermediate user_name variable. Please explain why this happens and how to avoid creating an extra variable?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Velko, 2018-04-04
@AL_3

In your case, you're losing this, which is equal to the component's instance. To "not lose" it, use an arrow function.
From documentation :

computed: {
  incomingActive() {
    this.messages.forEach((message) => {
      alert('user_name is: ' + this.user);
      /* ... */
      return incomingActive;
    });
  },
},

A
Alexander Aksentiev, 2018-04-04
@Sanasol

ryanmorr.com/understanding-scope-and-context-in-ja...
https://habrahabr.ru/post/149516/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question