Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

javascript - VueJS accessing a method from another method

I'm using VueJS to make a simple enough resource management game/interface. At the minute I'm looking to activate the roll function every 12.5 seconds and use the result in another function. At the moment though I keep getting the following error:

Uncaught TypeError: Cannot read property 'roll' of undefined(...)

I have tried:

  • app.methods.roll(6);
  • app.methods.roll.roll(6);
  • roll.roll()
  • roll()

but can't seem to access the function. Anyone any ideas how I might achieve this?

methods: {

  // Push responses to inbox.
  say: function say(responseText) {
    console.log(responseText);
    var pushText = responseText;
    this.inbox.push({ text: pushText });
  },

  // Roll for events
  roll: function roll(upper) {
    var randomNumber = Math.floor(Math.random() * 6 * upper) + 1;
    console.log(randomNumber);
    return randomNumber;
  },

  // Initiates passage of time and rolls counters every 5 time units.
  count: function count() {
    function counting() {
      app.town.date += 1;
      app.gameState.roll += 0.2;

      if (app.gameState.roll === 1) {
        var result = app.methods.roll(6);
        app.gameState.roll === 0;
        return result;
      }
    }

    setInterval(counting, 2500);

    ...

    // Activates the roll at times.
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can access these methods directly on the VM instance, or use them in directive expressions. All methods will have their this context automatically bound to the Vue instance.

Vue API Guide on methods

Within a method on a Vue instance you can access other methods on the instance using this.

var vm = new Vue({
  ...
  methods: {
    methodA() {
      // Method A
    },
    methodB() {
      // Method B

      // Call `methodA` from inside `methodB`
      this.methodA()
    },
  },
  ...
});

To access a method outside of a Vue instance you can assign the instance to a variable (such as vm in the example above) and call the method:

vm.methodA();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...