vuejs中method中的方法可以互相调用吗,在methods中调用后变量的作用于是怎样的?
new Vue({ el: '#app', data: { test:111, }, methods: { test1:function(){ alert(this.test) }, test2:function(){ alert("this is test2") alert(this.test) //test3调用时弹出undefined }, test3:function(){ this.$options.methods.test2(); } }})
解决方案
methods中的function中的this指向vue实例,其他的没什么
这种调用方式是直接访问test2函数,没有任何的this绑定,所以肯定访问不到
this.$options.methods.test2();
而直接调用this.test2(),内部肯定做了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) }}