Search code examples
javascriptvue.jsnuxt.jsvue-mixin

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


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

  }
})

Solution

  • 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();.

    const methods = {
    
      a() {
        const render = () => {
          this.b()
        }
        render()
      },
    
      b() {
        alert('testme')
      }
    
    }
    
    methods.a()