【问题标题】:Laravel Echo Vue Js TypeError: Cannot read property 'push' of undefinedLaravel Echo Vue Js TypeError:无法读取未定义的属性“推送”
【发布时间】:2016-12-04 06:17:57
【问题描述】:

我遇到了一个问题,尤其是 Vue Js,希望有人能指出我正确的方向。我正在使用连接到 Pusher 的 Laravel 的 Echo 功能。我目前正在从 pusher 那里取回数据,那部分很好而且很花哨。我似乎无法弄清楚的问题在于客户端代码。我正在尝试将来自推送器的新项目添加到我页面上已经存在的项目中。但是,当我在 Echo 通道块中使用 this.items.push() 时,我收到一个带有 TypeError 的控制台错误:无法读取未定义的属性“push”。我认为“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>

【问题讨论】:

    标签: laravel-5 vue.js pusher


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2019-11-15
      • 1970-01-01
      • 2018-05-08
      • 2020-04-20
      • 2017-11-23
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多