vuejs中methods中的互相调用

vuejs中methods中的方法可以互相调用吗

如一下的代码,想要在 test3 中调用 test2 的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
new Vue({
el: '#app',
data: {
test: 'test',
},
methods: {
test1: function() {
alert(this.test)
},
test2: function() {
alert("this is test2")
alert(this.test)
},
test3: function() {
this.test2();
//
}
}
})

methods中的function中的this指向vue实例,没有任何的this绑定,所以肯定访问不到。

可以尝试

1
this.$options.methods.test2.bind(this)();

这是vue的调用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Setup instance methods. Methods must be bound to the
* instance since they might be passed down as a prop to
* child components.
*/
Vue.prototype._initMethods = function() {
var methods = this.$options.methods
if (methods) {
for (var key in methods) {
this[key] = bind(methods[key], this)
}
}
}

function bind(fn, ctx) {
return function(a) {
var l = arguments.length
return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx)
}
}

The Why·Liam·Blog by WhyLiam is licensed under a Creative Commons BY-NC-ND 4.0 International License.

WhyLiam创作并维护的Why·Liam·Blog采用创作共用保留署名-非商业-禁止演绎4.0国际许可证

本文首发于Why·Liam·Blog (https://blog.naaln.com),版权所有,侵权必究。

本文永久链接:https://blog.naaln.com/2017/01/vuejs-call-method/