vue methods中一个方法调用另一个方法

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

 

posted @ 2018-11-07 18:49  还记得你的呢喃  阅读(3751)  评论(0)    收藏  举报