Vue mixins in Laravel Inertia

2.5k views Asked by At

I'm trying to create a global helper function via Vue mixin on a Laravel Inertia project to no avail:

//app.js
Vue.mixin({
    methods: {
        myFunction() {
            return 'Returnign from myFunction';
        },
    },
});

new Vue({
...
}).$mount(app);

.

//MyComponent.vue
console.log(myFunction()); // ReferenceError: myFunction is not defined

On a standalone Vue.JS project, this works. Maybe there's something behind the scene in Inertia that prevents the mixin from loading. Can somebody help me understand why this is happening?

Thank you.

2

There are 2 answers

0
Kim De Guzman On

you need () on your function

Vue.mixin({
    methods: {
        myFunction() {
            return 'Returnign from myFunction';
        },
    },
});

and then you missed this before your mixin function

console.log(this.myFunction());
    
0
Willower On

You need to add the function in the mixin of the createInertiaApp method in your app.js file.

For instance:

createInertiaApp({
  resolve: (name) => require(`./Pages/${name}.vue`),
  setup ({ el, app, props, plugin }) {
    return createApp({ render: () => h(app, props) })
      .use(plugin)
      .mixin({
        methods: {
          myFunction: () => {
            return 'Returning from myFunction';
          }
        }
      })
      .mount(el)
  }
})