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

查看:32
本文介绍了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:

未捕获的类型错误:无法读取 undefined(...) 的属性 'roll'

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

我试过了:

  • 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天全站免登陆