Martyn Ball
Martyn Ball

Reputation: 4885

Laravel and VueJS, access Vue instance.

I want to change a data property and run a method on my Vue instance within Laravel. However due to using webpack and laravel I can't seem to access the instance how I would expect to:

So window.app doesn't appear to be the correct instance of my Vue class.

Below is the Blade View i'm loading, as you can see I append a script tag to my main layout.blade.php, simply trying to change the Vue instance data property, and run a method.

@push('scripts')
    <script>
        app.unsaved = true;
        app.triggerEvent(null, 'models', null);
    </script>
@endpush

Below is part of my app.js (resources/assets/js/app.js):

const app = new Vue({
    el: '#app',
    components: {
        'models-select': ModelsSelect
    },
    data: {
        showModel: false,
        unsaved: false
    },
    mounted: function() {

        let _self = this;

        (function() {

            document.querySelectorAll("input, textarea, select").forEach(function(e) {
                e.addEventListener('change', function() {
                    _self.unsaved = true;
                    e.classList.add('is-changed');
                });
            });

            function unloadPage(){
                if (_self.unsaved) return 'You appear to have un-saved changes!';
            }

            window.onbeforeunload = unloadPage;

        })();

    },
    methods: {

        triggerEvent: function(event, target, property)
        {
            app.$refs[target].update(event, property);
        }

As you can see i'd expect to manipulate the Vue instance through the global app variable I have defined within the app.js. However this doesn't appear to be the case.

I get the following error when running the triggerEvent method:

app.triggerEvent is not a function

Upvotes: 0

Views: 2197

Answers (1)

George Hanson
George Hanson

Reputation: 3030

In your app.js file, change const app = new Vue({ to window.app = new Vue({.

Then within your <script> tags, change it to this.

<script>
    window.app.unsaved = true;
    window.app.triggerEvent(null, 'models', null);
</script>

Upvotes: 3

Related Questions