min*_*min 6 laravel vue.js laravel-echo
在我的 TaskList.vue 中,我有以下代码:
<template>
<div>
<ul>
<li v-for="task in tasks" v-text="task"></li>
</ul>
<input type="text" v-model="newTask" @blur="addTask">
</div>
</template>
<script>
export default {
data(){
return{
tasks: [],
newTask: ''
}
},
created(){
axios.get('tasks')
.then(
response => (this.tasks = response.data)
);
Echo.channel('task').listen('TaskCreated', (data) => {
this.tasks.push(data.task.body);
});
},
methods:{
addTask(){
axios.post('tasks', { body: this.newTask })
this.tasks.push(this.newTask);
this.newTask = '';
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
当我点击 axios.post('tasks') 端点时,我在当前选项卡中得到了重复的结果,我输入了该值,而另一个选项卡只有 1 个正确的值。
为了避免这种情况,我尝试使用 broadcast(new TaskCreated($task))->toOthers();
或者
I put $this->dontBroadcastToCurrentUser() in the construct of my TaskCreated.php
However, both methods are not working. Any idea why?
The image below is from network tab of mine. One of it is pending, is that what caused the problem?
https://ibb.co/jpnsnx (sorry I couldn't post image as it needs more reputation)
我通过使用 axios 帖子手动发送 X-Socket-Id 在我的 Laravel Spark 项目中解决了这个问题。
文档说,如果您使用 vue 和 axios,会自动添加标头,但对我来说(因为 spark?)却不是。
下面是一个示例,显示我如何使用 Laravel Echo 中的活动 socketId 手动将 X-Socket-Id 标头添加到 axios 帖子:
axios({
method: 'post',
url: '/api/post/' + this.post.id + '/comment',
data: {
body: this.body
},
headers: {
"X-Socket-Id": Echo.socketId(),
}
})
Run Code Online (Sandbox Code Playgroud)
Laravel 在使用 $this->dontBroadcastToCurrentUser() 时查找头 X-Socket-ID;通过这个 ID,Laravel 识别出要从事件中排除的用户(当前用户)。
您可以为请求添加拦截器,您可以在其中将套接字实例的 id 添加到每个请求的标头中:
/**
* Register an Axios HTTP interceptor to add the X-Socket-ID header.
*/
Axios.interceptors.request.use((config) => {
config.headers['X-Socket-ID'] = window.Echo.socketId() // Echo instance
// the function socketId () returns the id of the socket connection
return config
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3336 次 |
| 最近记录: |