0

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

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I thought that by defining the const in the global space it would get assigned to the window. Thanks, this works.
No problem. When Webpack transpiles it down, it will just change it from a const to a var - so it won't be available on the window object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.