我无法在JavaScript函数内调用混合函数。

huangapple go评论61阅读模式
英文:

I can't call a mixin function inside a javascript function

问题

我正在使用 Nuxt.js 进行一个小项目,目前我已经创建了一个使用 mixin 的插件,如你所见,但我不知道为什么函数 b 在渲染函数内部不起作用:

import Vue from 'vue'

Vue.mixin({
  methods: {

    a () {
      const render = function () {
        this.b()
      }
      render()
    },

    b () {
      alert('testme')
    }

  }
})
英文:

i'm working on a small project using nuxt.js and right now i have created a plugin using mixin as you can see, but i don't know why function b doesn't work inside render function :

import Vue from 'vue'


Vue.mixin({
  methods: {

    a () {
      const render = function () {
        this.b()
      }
      render()
    },

    b () {
      alert('testme')
    }

  }
})

答案1

得分: 3

自从您使用function关键字来定义render时,其中的this引用的是调用上下文(a),而该上下文没有b属性。

解决方案是使用箭头函数:const render = () => this.b();

const methods = {

  a() {
    const render = () => {
      this.b()
    }
    render()
  },

  b() {
    alert('testme')
  }

}

methods.a()
英文:

Since you used the function keyword to define render the this therein refers to the calling context (a) which has no property b.

The solution is to use an arrow function: const render = () => this.b();.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const methods = {

  a() {
    const render = () =&gt; {
      this.b()
    }
    render()
  },

  b() {
    alert(&#39;testme&#39;)
  }

}

methods.a()

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月7日 02:04:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定