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: '....'
    },
  },
}),
5
  • 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. Commented Jun 16, 2018 at 15:33
  • Yes, openDialog is under methods... and I've added the data Commented Jun 16, 2018 at 15:35
  • Possible duplicate of VueJS: why is "this" undefined? Commented Jun 16, 2018 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. Commented Jun 16, 2018 at 15:36
  • Can't believe it was that... Thanks! Commented Jun 16, 2018 at 15:38

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.