artem0071
artem0071

Reputation: 2419

How to pass a variable from a function in the component in Vue?

How to pass a variable from a function in the component in Vue? This is my code:

 export default {
    name: 'app',
      data: function () {
        return{
          city1: '',
          city2: '',
          metr: 0
        }
      },
      created () {
        ymaps.ready(init);
        function init() {
        $data.city1 = 'sdf'; // ?this to data of component?

Upvotes: 0

Views: 1828

Answers (1)

Edmundo Santos
Edmundo Santos

Reputation: 8287

Because you created an new function, the this inside it will be not point to the Vue component, but to the this of the function itself.

You can use an arrow function, or save the reference of the this, then use it later.

created() {
  const self = this;

  ymaps.init(init);

  function init() {
    self.city1 = 'sdf';
  }
}

Or (better):

created() {
  const init = () => {
    this.city1 = 'sdf';
  }

  ymaps.init(init);
}

Upvotes: 2

Related Questions