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

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

未捕获的 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.
}
}
129838 次浏览

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

You can use vm.methodName();

Example:

let vm = new Vue({
el: '#app',
data: {},
methods: {
methodA: function () {
console.log('hello');
},
methodB: function () {
// calling methodA
vm.methodA();
}
},
})

let vm = new Vue({
el: '#testfunc',
data:{
sp1: "Hi I'm textbox1",
sp2: "Hi I'm textbox2"
},
methods:{
chsp1:function(){
this.sp1 = "I'm swapped from textbox2"
},
chsp2:function(){
this.sp2 = "I'm swapped from textbox1";
this.chsp1();
},
swapit:function(){
this.chsp2();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="testfunc">
<input type="text" :value="sp1"></span>
<input type="text" :value="sp2"></span>
<button @click="swapit()">Swap</button>
</div>