1

I want to point from the data attribute to a function on methods, but I can't get manage to find the correct way to do it.

this is my template (the part that is relevant):

      <v-tooltip
        left
        v-for="(actionData, action) in actions"
        :key="action"
      >
        <v-btn
          fab
          small
          @click="actionData.func"
          slot="activator"
        >
          <v-icon>{{ action }}</v-icon>
        </v-btn>
        <span>{{ actionData.alt }}</span>
      </v-tooltip>

this is my data:

  actions: {
    add: {
      func: () => openComponentStepper('demo'),
      alt: '....',
    },
    build: {
      func: () => this.openDialog('test'),
      alt: '....'
    },
    adjust: {
      func: () => {},
      alt: '....'
    },
    update: {
      func: () => this.openDialog('ttl'),
      alt: '....'
    },
  },

I have a function under methods called openDialog, but every time I'm tring to execute it from this pointer I have under data it throws me this error:

TypeError: _this.openDialog is not a function


This is the full data attribute:

data: () => ({
  rules: {},
  fab: false,
  descriptionHeaders: [],
  dialog: {
    target: false,
    title: '',
    fields: [],
    save: () => {},
  },
  ignoerdFields: ['ignore', 'monitor', 'target'],
  actions: {
    add: {
      func: () => openComponentStepper('demo'),
      alt: '....',
    },
    build: {
      func: () => this.openDialog('test'),
      alt: '....'
    },
    adjust: {
      func: () => {},
      alt: '....'
    },
    update: {
      func: () => this.openDialog('ttl'),
      alt: '....'
    },
  },
}),
Elon Salfati
  • 1,537
  • 6
  • 23
  • 46
  • I'm assuming you've defined `openDialog` in your methods. Can you show your whole `data` method? My first thought is that the `this` in the code you've shared isn't pointing to the vue instance. – thanksd Jun 16 '18 at 15:33
  • Yes, openDialog is under methods... and I've added the data – Elon Salfati Jun 16 '18 at 15:35
  • Possible duplicate of [VueJS: why is "this" undefined?](https://stackoverflow.com/questions/43929650/vuejs-why-is-this-undefined) – thanksd Jun 16 '18 at 15:35
  • 1
    Don't use an arrow function when defining your `data` method. Arrow functions bind `this` to the parent scope, which is not the Vue instance in this case. – thanksd Jun 16 '18 at 15:36
  • Can't believe it was that... Thanks! – Elon Salfati Jun 16 '18 at 15:38

1 Answers1

1

The problem is that you're using an arrow function for the data. You have to use the regular function syntax:

data: function() {
  return { /*...*/ }
}

Or, the modern version:

data() {
  return { /*...*/ }
}

This will make this point to what you expect it to point (and not the window).

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91