VueJS从另一个方法访问一个方法 [英] VueJS accessing a method from another method

查看:242
本文介绍了VueJS从另一个方法访问一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VueJS制作足够简单的资源管理游戏/界面.目前,我希望每12.5秒激活一次roll函数,并将结果用于另一个函数. 目前,尽管我不断出现以下错误:

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:

未捕获的TypeError:无法读取未定义(...)的属性'roll'

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

我尝试过:

  • app.methods.roll(6);
  • app.methods.roll.roll(6);
  • roll.roll()
  • roll()
  • 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.
  }
}

推荐答案

您可以直接在VM实例上访问这些方法,也可以在指令表达式中使用它们.所有方法的this上下文都将自动绑定到Vue实例.

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.

methods

在Vue实例上的方法中,您可以使用this访问实例上的其他方法.

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()
    },
  },
  ...
});

要访问Vue实例之外的方法,可以将该实例分配给变量(例如上例中的vm)并调用该方法:

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();

这篇关于VueJS从另一个方法访问一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆