Elon Salfati
Elon Salfati

Reputation: 1687

Point to methods from data | VueJS

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: '....'
    },
  },
}),

Upvotes: 1

Views: 391

Answers (1)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

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

Upvotes: 1

Related Questions