Search code examples
laravelvue.jsvuejs2vue-componentvuex

How to extend app.js methods/data/watch from laravel blade view file without creating components


I'm new in vue.js.

My app.js is:

import { store } from './store';
const app = new Vue({
    el: '#app',
    store,
    mounted(){
        ...
    },
    methods:{
        ...
    }
});

I'm using laravel and I don't want every time to create components for very small reason. Without making components app.js will be full of methods whose all are not useful in every pages. That's why I want a way to extend app.js from my home.blade.php file's

@section(scripts)
    <script>
        ...
    </script>
@endsection

(without creating any component).

Or, Updating/add in data:{ ... } & methods:{ ... } using that <script> .. </script> in *.blade.php


Solution

  • I've found a solution!

    Use Mixin

    Create mixin.js file besides app.js

    For example

    export var custom = {
      data: {
        show: true
      },
      methods: {
        hide: function(){
          this.show = false;
        }
      },
      watch: {
        ...
      },
    
      ...
    
    };
    

    and, in app.js file:

    import { store } from './store';
    import { custom } from './mixin';  //Import mixin
    window.app = new Vue({
        el: '#app',
        mixins: [custom],  // Add mixin var here
        store,
    });
    
    /*
      [note: for multiple: import {custom1, custom2, ...} and define [custom1, custom2, ...] ]
    */
    

    More details: Official Documentation