Vuejs中methods中的互相调用
如一下的代码,想要在 test3 中调用 test2 的代码。
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
绑定,所以肯定访问不到。
this.$options.methods.test2.bind(this)();
这是vue的调用方式
/** * 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) } }