VueJS从另一个方法访问一个方法

JavaScript

神乐古一

2020-03-11

我正在使用VueJS制作足够简单的资源管理游戏/界面。目前,我希望roll每12.5秒激活一次该功能,并将结果用于其他功能。目前,尽管我不断收到以下错误:

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

我试过了:

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

但似乎无法访问该功能。任何人有任何想法我将如何实现?

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

第588篇《VueJS从另一个方法访问一个方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
超威蓝喵 2020.03.11
created() 
{
    this.initialize();     
},
 methods: {
       async initialize()
         {
            //code here.......
            this.getExcellSheet();    //method call
         },
       async getExcellSheet()
         {
                      //code here.......
          }
  }
ItachiTom 2020.03.11

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

–关于的Vue API指南methods

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

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

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

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

vm.methodA();

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android