Laravel Echo Vue Js TypeError: 无法读取未定义的属性'push'



我有一个问题,尤其是在VUE JS的情况下,希望有人可以将我指向正确的方向。我使用的是Laravel的Echo功能,该功能连接到Pusher。我目前正在从Pusher那里收回数据,这是很好的花花公子。我似乎无法确定的问题在客户端代码上。我正在尝试将来自Pusher的新项目添加到我页面上已经存在的项目。但是,当我在回声通道块中使用this.items.push()时,我将收到带有TypeError的控制台错误:无法读取未定义的属性"推动"。我认为" this.items"不范围?

<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>

this的范围更改Echo.channel内部,您将this保存在不同的变量中,并且在内部使用该变量而不是this,这就是为什么它在Echo.channel外部完美工作,但是this.items内部是null,所以它投掷错误。您需要进行以下更改:

    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')
                });
        } 

相关内容

最新更新