vue.js methods中的方法互相调用时变量的作用域是怎样的?

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

http://runjs.cn/code/hv2gdiuf

阅读 34.8k
2 个回答

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

直接this.test1(), this.test2()

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题