0

I'm having an issue particularly with Vue Js hoping someone can point me in the right direction. I am using Laravel's Echo feature which is connected to Pusher. I currently am getting data back from pusher that part is fine and dandy. The issue I can't seem to figure out is on the client side code. I'm trying to add the new items coming from pusher to the already existing items on my page. However when I use this.items.push() within the Echo channel block I am receiving a console error with TypeError: Cannot read property 'push' of undefined. I am thinking that "this.items" is out of scope?

<div id="app">
    <ul id="example-1">
        <li v-for="item in items">
            @{{ item }}
        </li>
    </ul>
</div>

<script>
    new Vue({

        el: '#app',

        data: {
            items: []
        },
        mounted: function () {
            this.listen();
        },

        methods: {
            /**
             * Listen to the Echo channels
             */
            listen: function() {

                // pushed fine from here
                this.items.push("dddd");

                Echo.channel('test_channel')
                    .listen('OrderCreated', function(e) {
                        //TypeError: Cannot read property 'push' of undefined
                        this.items.push('elkqwejfh')
                    });
            }
        }
    });
</script>

1 Answer 1

1

scope of this changes inside Echo.channel, you have save this in a different variable and use that variable inside instead of this, That's why it work perfectly outside Echo.channel but inside this.items is null, so it throws error. You need to make following changes:

    methods: {
        /**
         * Listen to the Echo channels
         */
        listen: function() {

            // pushed fine from here
            this.items.push("dddd");
            var self = this
            Echo.channel('test_channel')
                .listen('OrderCreated', function(e) {
                    //TypeError: Cannot read property 'push' of undefined
                   self.items.push('elkqwejfh')
                });
        } 
Sign up to request clarification or add additional context in comments.

Comments

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.