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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM