Laravel Echo Vue Js TypeError: Cannot read property 'push' of undefined
Laravel Echo Vue Js TypeError: Cannot read property 'push' of undefined
我遇到了一个问题,尤其是 Vue Js 希望有人能指出我正确的方向。我正在使用连接到 Pusher 的 Laravel 的 Echo 功能。我目前正在从 pusher 取回数据,那部分很好而且很漂亮。我似乎无法弄清楚的问题是在客户端代码上。我正在尝试将来自 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>
this
的范围在 Echo.channel
内发生变化,您已将 this
保存在不同的变量中并在内部使用该变量而不是 this
,这就是它完美运行的原因在 Echo.channel
之外但在 this.items
内部是空的,所以它会抛出错误。您需要进行以下更改:
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')
});
}
我遇到了一个问题,尤其是 Vue Js 希望有人能指出我正确的方向。我正在使用连接到 Pusher 的 Laravel 的 Echo 功能。我目前正在从 pusher 取回数据,那部分很好而且很漂亮。我似乎无法弄清楚的问题是在客户端代码上。我正在尝试将来自 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>
this
的范围在 Echo.channel
内发生变化,您已将 this
保存在不同的变量中并在内部使用该变量而不是 this
,这就是它完美运行的原因在 Echo.channel
之外但在 this.items
内部是空的,所以它会抛出错误。您需要进行以下更改:
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')
});
}